我一直在用Python中的空格替換「 - 」。我搜索了堆棧溢出並嘗試了下面的代碼,但它沒有做我想要的。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
這裏是我的輸出:
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']
我知道文本1,文本2,和文字3是用一個項目是一個字符串中的每個列表。這可能是我忽略的小事,有什麼想法?
輸出1人如果你重新分配了替換返回值的工作......'strip'只用於結尾字符...其他2個循環字符按字符 –
你正在做幾件事情錯誤。請參閱[官方Python教程](https://docs.python.org/2.7/tutorial/index.html)。 – TigerhawkT3