【问题标题】:iterating over a tuple containing one string actually iterates over characters [duplicate]迭代包含一个字符串的元组实际上迭代字符[重复]
【发布时间】:2016-06-17 14:28:38
【问题描述】:

在迭代仅包含 1 个字符串的元组时,我注意到一个奇怪的行为:

foo = ("hello")
for entry in foo:
    print(entry)

输出:

h
e
l
l
o

但我希望这里只迭代一次,并连续输出“hello”。

如果我的元组包含 2 个条目,那就是发生了什么:

foo = ("hello", "world!")
for entry in foo:
    print(entry)

输出:

hello
world!

这是 CPython 实现中的错误吗? 更奇怪的是,如果我使用列表而不是元组,这不会发生:

foo = ["hello"]
for entry in foo:
    print(entry)

输出:

hello

【问题讨论】:

  • ('hello') 不是包含一个字符串的元组。这只是一个字符串。试试print(type(foo))
  • 要扩展 jonrsharpes 注释,定义 1 元素元组的正确方法是 ('hello',)
  • foo = 'hello', 就足够了。

标签: python string python-3.x tuples


【解决方案1】:

("hello") 不是元组 - 它是一个字符串,用括号括起来,在这种情况下没有意义。如果你想要一个单元素元组,你需要在值后面加一个逗号:

foo = ("hello",) 
# Here--------^

【讨论】:

  • 谢谢,对于重复的问题,抱歉。
【解决方案2】:

你有一个字符串而不是一个元组:

>>> type(('hello'))
<class 'str'>
>>> type(('hello',))
<class 'tuple'>

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2015-01-01
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2014-04-21
    相关资源
    最近更新 更多