【问题标题】:python: why does replace not work?python:为什么替换不起作用?
【发布时间】:2017-01-12 13:21:49
【问题描述】:

我编写了一个快速脚本来从保存在 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

【问题讨论】:

  • “不起作用”不是解释,您应该描述问题。 会发生什么?您尝试过什么解决方法?

标签: python replace openpyxl


【解决方案1】:
String.replace(substr)

原地没有发生,改成:

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

【讨论】:

    【解决方案2】:

    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://", "")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 2012-01-18
      • 2016-02-27
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      相关资源
      最近更新 更多