Changing one character in a string

前端 未结 11 1028
抹茶落季
抹茶落季 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 :).

提交回复
热议问题