我有一个python列表,我需要使它成为一个没有换行符的字符串。我有这个['1n2n2n,n6n2n9n,n7n1n3']
,我希望它是122,629,713
在一个字符串,而不是列表。这是我的列表代码:
follower = [driver.find_elements_by_xpath('//*[@id="__next"]/div/div/div[3]/div[2]/div[2]/div/div')[0].text]
follow = ''
for item in follower:
item = item.strip('n')
item = item.strip('[')
item = item.strip(']')
item = item.strip("'")
follow = follow + item
for item in follower:
follow += item
print(follow.replace("n",""))
如果必须替换多个字符,最简单的方法是使用正则表达式。您可以使用|
分隔字符串中的字符,并记住转义特殊字符。
import re
chars_to_remove = "n|'|[|]"
text = "1n2n2n,]n6n2n9n,[n7n1n3'"
re.sub(chars_to_remove, "", text)
输出:
'122,629,713'
我不确定你是否有一个字符串列表:
list_of_strings = ['1n2n2n,n6n2n9n,n7n1n3']
或者只是一个字符串:
string = '1n2n2n,n6n2n9n,n7n1n3'
如果您有一个字符串列表,只需使用for循环来获取每个字符串,然后使用下面的代码来执行您的要求,其他只需遍历字符串
# CASE 1: you have a list of strings
for string in list_of_strings:
fixed_string = ""
for char in string:
if char != 'n'
fixed_string += char
print(fixed string)
# CASE 2: you just have the string
fixed_string = ""
for char in string:
if char != 'n'
fixed_string += char
print(fixed_string)
两种情况下都应该遍历字符串,如果它们不是换行字符(n),则将它们添加到新字符串中。
给定:
>>> l=['1n2n2n,n6n2n9n,n7n1n3']
每个字符串上的列表推导式和.replace
:
>>> [e.replace('n','') for e in l]
['122,629,713']
我所理解的是你有一个列表a=['1n2n2n,n6n2n9n,n7n1n3']
,你想从它删除n
,你想要的结果是[122,629,713]
。然而,list a
中有一个错误,因为python将列表中的项目视为一个项目,a should be a=['1n2n2n','n6n2n9n','n7n1n3']
a=['1n2n2n','n6n2n9n','n7n1n3']
b=""
index=0
for i in a:
c=i.replace("n","")
b+=f"{c},"
if index==(len(a)-1):
b=b[0:len(b)-1]
index+=1
print(b)
#The outcome will be `122,629,713`
如果你想要[122,629,713]
的结果,那么在for-loop
后面加上
b=b.split(",")
# Now the outcome will be `[122,629,713]`