python:为什么替换不起作用?

时间:2017-01-12 13:21:50

标签: python replace openpyxl

我写了一个快速脚本,从excel列保存的网站地址列表中删除'http://'子字符串。功能替换,但不起作用,我不明白为什么。

from openpyxl import load_workbook

def rem(string):
    print string.startswith("http://")    #it yields "True"
    string.replace("http://","")
    print string, type(string)    #checking if it works (it doesn't though, the output is the same as the input)

wb = load_workbook("prova.xlsx")
ws = wb["Sheet"]

for n in xrange(2,698):
    c = "B"+str(n)
    print ws[c].value, type(ws[c].value)   #just to check value and type (unicode)
    rem(str(ws[c].value))    #transformed to string in order to make replace() work

wb.save("prova.xlsx")    #nothing has changed

2 个答案:

答案 0 :(得分:4)

String.replace(substr)

不会发生,将其更改为:

string = string.replace("http://","")

答案 1 :(得分:-1)

string.replace(old, new[, max])只返回一个值 - 它不会修改string。例如,

>>> a = "123"
>>> a.replace("1", "4")
'423'
>>> a
'123'

您必须将字符串重新分配给其修改后的值,如下所示:

>>> a = a.replace("1", "4")
>>> a
'423'

所以在你的情况下,你想要改为写

string = string.replace("http://", "")