在C ++中,我可以std::string像這樣迭代:std::string str = "Hello World!";for (int i = 0; i < str.length(); ++i){ std::cout << str[i] << std::endl;}如何在Python中遍歷字符串?
3 回答

慕勒3428872
TA貢獻1848條經(jīng)驗 獲得超6個贊
如果在遍歷字符串時需要訪問索引,請使用enumerate():
>>> for i, c in enumerate('test'):
... print i, c
...
0 t
1 e
2 s
3 t

慕尼黑的夜晚無繁華
TA貢獻1864條經(jīng)驗 獲得超6個贊
只是為了做出更全面的答案,如果您真的想將方釘強行塞入圓孔中,則對字符串進行迭代的C方法可以在Python中應(yīng)用。
i = 0
while i < len(str):
print str[i]
i += 1
但是話又說回來,當字符串具有固有的可迭代性時,為什么要這樣做呢?
for i in str:
print i
添加回答
舉報
0/150
提交
取消