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

Pig*_*gna 0 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
Run Code Online (Sandbox Code Playgroud)

小智 6

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

\n\n
>>> a = "123"\n>>> a.replace("1", "4")\n\'423\'\n>>> a\n\'123\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
>>> a = a.replace("1", "4")\n>>> a\n\'423\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以在你的情况下,你会想写

\n\n
string = string.replace("http://", "")\n
Run Code Online (Sandbox Code Playgroud)\n


Nic*_*ick 5

String.replace(substr)
Run Code Online (Sandbox Code Playgroud)

没有就位,请将其更改为:

string = string.replace("http://","")
Run Code Online (Sandbox Code Playgroud)