在Python中,我一直在用空格替换“-”。我已经搜索了堆栈溢出并尝试了下面的代码,但它没有达到我想要的效果。在
import string
text1 = ['why-wont-these-dashes-go-away']
for i in text1:
str(i).replace("-", " ")
print "output 1: "
print text1
text2 = ['why-wont-these-dashes-go-away']
text2 = [x.strip('-') for x in text2]
print "output 2: "
print text2
text3 = ['why-wont-these-dashes-go-away']
text3 = [''.join(c for c in s if c not in string.punctuation) for s in text3]
print "output 3: "
print text3
text4 = ['why-wont-these-dashes-go-away']
text4 = [' '.join(c for c in s if c not in string.punctuation) for s in text3]
print "output 4: "
print text4
以下是我的输出:
^{pr2}$我想要的是:
['why wont there dashes go away']
我知道text1、text2和text3每个列表都有一个字符串。可能是我忽略了一些小事,有什么想法吗?在
text1是一个列表,该列表在第0个位置有一个字符串“why wot this dash got away”。因此,只需使用:
您有以下错误:
方法1:将返回值
replace
分配给任何变量,不是方法2:Strip只从字符串的开始和结尾剥离字符
方法3和4:使用空字符串(
''
)或空格(' '
)连接每个字符,不是每个单词。在你可以试试这个方法:
或者这个:
^{pr2}$您在循环中所做的操作对列表中的数据没有影响,您应该使用数据创建一个新列表:
相关问题 更多 >
编程相关推荐