【问题标题】:Python 3: "next" attribute in str_iterator objectPython 3:str_iterator 对象中的“下一个”属性
【发布时间】:2019-09-29 04:03:59
【问题描述】:

(不确定告诉 Python 版本是否有帮助,所以我将把它留在标题中)

您好,我再次询问有关“next()”函数的问题。

此代码用于检查您的输入是否包含“o”或“re”:


input = input("Your Oreo set: ").lower()
oreo = iter(input)
print(input)

res = """wait. something wrong has happened...
did you even enter anything lolz"""

for ch in oreo:

    if (ch == "o") or ((ch == "r") and (ch.next() == "e")):
        res = "hi, the oreo is being made..."

    else:
        res = "hi, this is not an oreo pattern. you can only enter either \'o\' or \'re\' to make one."

我使用了 next() 函数,以便我可以检查输入是否有“re”,其中包含两个字符

但我不断收到 AttrbueError 说字符串对象没有“next()”方法。 我想我可以使用 iter() 函数来允许输入是可迭代的??

所以这是我得到的问题: 我怎样才能允许输入(又名“oreo”变量)使用 next() 方法??

【问题讨论】:

  • and (ch.next() == "e"))?您是否尝试检查下一个值?
  • @roganjosh 是的
  • 代码对我来说没有任何意义。 oreo = iter(input) 你想让它单独遍历每个字符吗?
  • @roganjosh 你是对的
  • 从迭代器中获取下一个值的方法是next(it),但ch不是迭代器。

标签: python string iterator iteration


【解决方案1】:

像这样逐个字符地迭代字符串是没有意义的。如果这行得通,无论如何你都会得到每个字符的打印输出。您可以只使用in 并提供're' 作为子字符串来解决在找到'r' 的情况下检查下一个字符的问题。

inp = input("Your Oreo set: ").lower() # don't call your variable "input"
if 'o' in inp or 're' in inp:
    res = "hi, the oreo is being made..."
else:
    res = "hi, this is not an oreo pattern. you can only enter either \'o\' or \'re\' to make one."

【讨论】:

  • @randomkat2035 迭代器在这里毫无意义,因为您已经在内存中拥有完整的字符串;一个接一个地产生字符并没有什么好处(字符串是序列,所以这隐含地就是这样做的)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多