python: 为什么替换不起作用?
python: why does replace not work?
我编写了一个快速脚本,用于从保存在 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
String.replace(substr)
没有发生到位,改成:
string = string.replace("http://","")
string.replace(old, new[, max])
只是 returns 一个值——它不会修改 string
。例如,
>>> a = "123"
>>> a.replace("1", "4")
'423'
>>> a
'123'
您必须 re-assign 字符串为其修改后的值,如下所示:
>>> a = a.replace("1", "4")
>>> a
'423'
所以在你的情况下,你会想改为写
string = string.replace("http://", "")
我编写了一个快速脚本,用于从保存在 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
String.replace(substr)
没有发生到位,改成:
string = string.replace("http://","")
string.replace(old, new[, max])
只是 returns 一个值——它不会修改 string
。例如,
>>> a = "123"
>>> a.replace("1", "4")
'423'
>>> a
'123'
您必须 re-assign 字符串为其修改后的值,如下所示:
>>> a = a.replace("1", "4")
>>> a
'423'
所以在你的情况下,你会想改为写
string = string.replace("http://", "")