How can I copy a Python string?

后端 未结 5 967
深忆病人
深忆病人 2020-12-12 23:38

I do this:

a = \'hello\'

And now I just want an independent copy of a:

import copy

b = str(a)
c = a[:]
d = a          


        
5条回答
  •  一整个雨季
    2020-12-12 23:46

    I'm just starting some string manipulations and found this question. I was probably trying to do something like the OP, "usual me". The previous answers did not clear up my confusion, but after thinking a little about it I finally "got it".

    As long as a, b, c, d, and e have the same value, they reference to the same place. Memory is saved. As soon as the variable start to have different values, they get start to have different references. My learning experience came from this code:

    import copy
    a = 'hello'
    b = str(a)
    c = a[:]
    d = a + ''
    e = copy.copy(a)
    
    print map( id, [ a,b,c,d,e ] )
    
    print a, b, c, d, e
    
    e = a + 'something'
    a = 'goodbye'
    print map( id, [ a,b,c,d,e ] )
    print a, b, c, d, e
    

    The printed output is:

    [4538504992, 4538504992, 4538504992, 4538504992, 4538504992]
    
    hello hello hello hello hello
    
    [6113502048, 4538504992, 4538504992, 4538504992, 5570935808]
    
    goodbye hello hello hello hello something
    

提交回复
热议问题