后浪云Python教程:python怎样遍历字符串

python遍历字符串的方法:可以直接通过for循环进行遍历,具体方法如:【strs = 'abcd' for ch in strs: print(ch)】。还可以利用下标或迭代器来进行遍历。

后浪云Python教程:python怎样遍历字符串插图

可以使用以下几种方法:

(推荐教程:Python入门教程)

1、直接进行遍历

strs = 'abcd'
for ch in strs:
    print(ch)

2、利用下标遍历

strs = 'abcd'
for index, ch in enumerate(strs):
    print(index,end=' ')
    print(ch)

3、利用range进行遍历

strs = 'abcd'
for index in range(len(strs)):
    print(strs[index], end=' ')

4、利用迭代器

strs = 'abcd'
for ch in iter(strs):
    print(ch)
THE END