问题描述
在for循环中声明一个variable1时,我给它分配了一些字符串>>>而给定另一个variable2 .....当提供输出时,它显示variable1 len为1,variable2有8,这是如何工作的? ?
for variable1 in "something is here please help":
print(variable1)
variable2 = "abcdefgh"
print(len(variable1))
print(len(variable2))
解决方法
for 循环用于迭代序列(即列表、元组、字典、集合或字符串)。在您的情况下,序列是一个字符串(“这里有东西请帮忙”)并且迭代器应该遍历所有字母:'s','o','m','t'...这就是为什么它的长度是1 表示一个字符。请参考:https://www.w3schools.com/python/python_for_loops.asp#:~:text=A%20for%20loop%20is%20used,other%20object%2Dorientated%20programming%20languages。