在Python中,我可以将整个单词拆分为多个字母变量,例如:
word = 'because'
会给:
1 = 'b'
2 = 'e'
3 = 'c'
4 = 'a'
5 = 'u'
6 = 's'
7 = 'e'
答案 0 :(得分:2)
动态变量是一种不好的做法,应该避免。很容易忘记它们,不小心遮盖它们等等。
为什么不使用dictionary?
>>> word = 'because'
>>> dct = dict(enumerate(word, 1))
>>> dct
{1: 'b', 2: 'e', 3: 'c', 4: 'a', 5: 'u', 6: 's', 7: 'e'}
>>> dct[1] # Would be the same as 'var_1'
'b'
>>> dct[5] # Would be the same as 'var_5'
'u'
>>>
正如您所看到的,它与动态变量名称大致相同,只是数据干净地存储在字典对象中。
答案 1 :(得分:0)
我不完全确定您要问的是什么,但您可以使用索引来访问字符串的各个字符:
word = "because"
print(word[0]) # Prints "b"
print(word[1]) # Prints "e"
print(word[2]) # Prints "c"
print(word[3]) # Prints "a"
print(word[4]) # Prints "u"
print(word[5]) # Prints "s"
print(word[6]) # Prints "e"