How to set a different variable for every character of the string

六月ゝ 毕业季﹏ 提交于 2020-06-27 06:39:06

问题


Would it be possible to take a string and set a different variable for every character of the string? In other words..

string='Hello'

#Do some thing to split up the string here

letter_1= #The first character of the variable 'string'
letter_2= #The second character of the variable 'string'
#...
letter_5= #The fifth character of the variable 'string'

回答1:


In Python, strings are immutable, so you can't change their characters in-place. However if you try to access by index then you get:

TypeError: 'str' object does not support item assignment

In order to change a character of the string,firstly convert the string into a list of characters,make your desired modification and then make a new variable to store the the new string made by using .join() Take this for example:

string='Hello' 
print(string)
s = list(string)
s[0] = "M"
new_string = ''.join(s)
print(new_string)

End result:

Hello
Mello


来源:https://stackoverflow.com/questions/40682550/how-to-set-a-different-variable-for-every-character-of-the-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!