Changing one character in a string

前端 未结 11 841
抹茶落季
抹茶落季 2020-11-22 03:21

What is the easiest way in Python to replace a character in a string?

For example:

text = \"abcdefg\";
text[1] = \"Z\";
           ^
相关标签:
11条回答
  • 2020-11-22 04:10

    Actually, with strings, you can do something like this:

    oldStr = 'Hello World!'    
    newStr = ''
    
    for i in oldStr:  
        if 'a' < i < 'z':    
            newStr += chr(ord(i)-32)     
        else:      
            newStr += i
    print(newStr)
    
    'HELLO WORLD!'
    

    Basically, I'm "adding"+"strings" together into a new string :).

    0 讨论(0)
  • 2020-11-22 04:13

    Don't modify strings.

    Work with them as lists; turn them into strings only when needed.

    >>> s = list("Hello zorld")
    >>> s
    ['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
    >>> s[6] = 'W'
    >>> s
    ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
    >>> "".join(s)
    'Hello World'
    

    Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.

    0 讨论(0)
  • 2020-11-22 04:17

    Strings are immutable in Python, which means you cannot change the existing string. But if you want to change any character in it, you could create a new string out it as follows,

    def replace(s, position, character):
        return s[:position] + character + s[position+1:]
    

    replace('King', 1, 'o')
    // result: Kong

    Note: If you give the position value greater than the length of the string, it will append the character at the end.

    replace('Dog', 10, 's')
    // result: Dogs

    0 讨论(0)
  • 2020-11-22 04:22

    Like other people have said, generally Python strings are supposed to be immutable.

    However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.

    Here is an example where I use the technique to clear a string.

    Mark data as sensitive in python

    I mention this for the sake of completeness, and this should be your last resort as it is hackish.

    0 讨论(0)
  • 2020-11-22 04:23
    new = text[:1] + 'Z' + text[2:]
    
    0 讨论(0)
提交回复
热议问题