如何为字符串的每个字符设置不同的变量

2024-04-25 00:00:24 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以获取一个字符串,并为该字符串的每个字符设置不同的变量?换句话说

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'

Tags: oftheto字符串hellostringsome字符
1条回答
网友
1楼 · 发布于 2024-04-25 00:00:24

在Python中,字符串是不可变的,因此不能在适当的位置更改它们的字符。 但是,如果尝试按索引访问,则会得到:

TypeError: 'str' object does not support item assignment

要更改字符串的字符,请首先将字符串转换为字符列表,进行所需的修改,然后生成一个新变量来存储使用.join()生成的新字符串。例如:

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

最终结果:

Hello
Mello

相关问题 更多 >