Why doesn't calling a Python string method do anything unless you assign its output?

前端 未结 2 2189
鱼传尺愫
鱼传尺愫 2020-11-21 04:24

I try to do a simple string replacement, but I don\'t know why it doesn\'t seem to work:

X = \"hello world\"
X.rep         


        
2条回答
  •  感情败类
    2020-11-21 04:58

    This is because strings are immutable in Python.

    Which means that X.replace("hello","goodbye") returns a copy of X with replacements made. Because of that you need replace this line:

    X.replace("hello", "goodbye")
    

    with this line:

    X = X.replace("hello", "goodbye")
    

    More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace,strip,translate,lower/upper,join,...

    You must assign their output to something if you want to use it and not throw it away, e.g.

    X  = X.strip(' \t')
    X2 = X.translate(...)
    Y  = X.lower()
    Z  = X.upper()
    A  = X.join(':')
    B  = X.capitalize()
    C  = X.casefold()
    

    and so on.

提交回复
热议问题