【问题标题】:How to loop through a string of letters and numbers and identify which are numbers? [duplicate]如何遍历一串字母和数字并识别哪些是数字? [复制]
【发布时间】:2021-09-05 00:02:31
【问题描述】:

我正在编写一些代码,并想添加一个条件语句,这样当我们循环遍历下面的 stringg 时,如果我们命中一个整数,那么......我们会做一些事情(不管怎样)

stringg = "3[a]2[bc]"

但问题是,即使 3 和 2 目前也是字符串 - 我如何在检查每个字符是否为整数时遍历 stringg?

for i in stringg: 
    if isinstance(i,int): 
        print("Hello")

上面的循环returns nothing 到我上面的观点。任何想法如何实现上述目标?

想到的另一件事是在循环时执行 int(i),但我不知道如何执行此操作。

【问题讨论】:

  • python 中的字符串具有“isdigit”和“isnumeric”作为您可以使用的函数。
  • 建议的副本上接受的答案在这里不起作用。 OP 不能被空格分割。 2nd highest voted one 也涵盖了这种情况。

标签: python string loops


【解决方案1】:
stringg = "3[a]2[bc]"

for ch in stringg:
    if ch.isnumeric():
        print(ch)

【讨论】:

  • 考虑解释你的代码
猜你喜欢
  • 2012-04-02
  • 1970-01-01
  • 2017-10-10
  • 2021-07-18
  • 2020-03-30
  • 2019-03-28
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多