首页 > 文章列表 > python怎样遍历字符串

python怎样遍历字符串

Python 字符串
265 2022-08-07

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

可以使用以下几种方法:

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)