函数replace()似乎不起作用

时间:2019-08-09 08:56:36

标签: python python-3.x

这是我的作业问题:

  

编写一系列语句,这些语句产生一个名为newA的副本,   其中字符“。”,“,”,“;”和“ \ n”已替换为   空格。

然后我使用了replace()函数来执行此操作,但是当我执行newA时,输出是a,而不是替换。

这是我到目前为止所做的:

a = ' ' 'It was the best of times, it was the worst of times; it was the age of wisdom, it was the age of foolishness; it was the epoch of belief, it was the epoch of incredulity; it was ...' ' '

newA = a.replace('.', ' ')

newA = a.replace(',', ' ')

newA = a.replace(';', ' ')

newA = a.replace('\n', ' ')

为什么不起作用?如何使它起作用?

3 个答案:

答案 0 :(得分:3)

第一次使用newA是因为分配给newA的替换字符串是

newA = a.replace('.', ' ')
newA = newA.replace(',', ' ')
newA = newA.replace(';', ' ')

newA = newA.replace('\n', ' ')

答案 1 :(得分:2)

您正在对原始字符串a进行操作。您需要将最后三个替换项从a.replace更改为newA.replace

答案 2 :(得分:2)

我认为您应该采用这种方式:

a = ' ' 'It was the best of times, it was the worst of times; it was the age of wisdom, it was the age of foolishness; it was the epoch of belief, it was the epoch of incredulity; it was ...' ' '

newA = a.replace('.', ' ')  
newA = newA.replace(',', ' ')    
newA = newA.replace(';', ' ')    
newA = newA.replace('\n', ' ')

a = ' ' 'It was the best of times, it was the worst of times; it was the age of wisdom, it was the age of foolishness; it was the epoch of belief, it was the epoch of incredulity; it was ...' ' '

newA = a.replace('.', ' ').replace(',', ' ').replace(';', ' ').replace('\n', ' ')

在您的示例中,您反复在初始'a'变量上使用replace。