【发布时间】:2016-07-04 16:30:25
【问题描述】:
我一直坚持在 Python 中用空格替换“-”。我搜索了 Stack Overflow 并尝试了下面的代码,但它并没有达到我想要的效果。
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
这是我的输出:
output 1:
['why-wont-these-dashes-go-away']
output 2:
['why-wont-these-dashes-go-away']
output 3:
['whywontthesedashesgoaway']
output 4:
['w h y w o n t t h e s e d a s h e s g o a w a y']
这就是我想要的:
['why wont there dashes go away']
我知道 text1、text2 和 text3 是每个列表,其中一个项目是一个字符串。这可能是我忽略的一些小东西,有什么想法吗?
【问题讨论】:
-
如果您将replace 的返回值重新分配给列表,则输出1 将起作用...
strip仅用于结束字符...另外2 个逐字符循环 -
你做错了几件事。请参阅official Python tutorial。
标签: python string list replace