python 通过for循环及while循环遍历字符串中的字符

下面是代码,for循环直接循环遍历即可,while则需要iter生成迭代器再去循环。

ls = input('请输入字符串:' )
#for循环
for j in ls:
    print(j)
print('这是一条分割线')
#while循环
ite = iter(ls)
while True:
    try:
        each = next(ite)
    except StopIteration:
        break
    print(each)

下面是输出结果
请输入字符串:qwe
q
w
e
这是一条分割线
q
w
e

猜你喜欢

转载自blog.csdn.net/qq_37823979/article/details/107662364