问题
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