【问题标题】:How to convert string number to int and avoid the string text before convert如何将字符串数字转换为int并避免转换前的字符串文本
【发布时间】:2021-04-02 14:21:39
【问题描述】:

我想创建检查条件字符串是否为字符串编号 那么,我该如何在 python 中做呢

x = "String"
y = "12"

if x is string:
   print("this is string")
if y is string:
   print("this is not string")

【问题讨论】:

标签: python string if-statement


【解决方案1】:

你可以试试这样的:

array = ["String", "12"]

for item in array:
  try:
    int(item)
    print(f"{item} is not string")
  except:
    print(f"{item} is string")

【讨论】:

    【解决方案2】:

    您可以使用.isdigit() 方法来实现这一点。

    x = "String"
    y = "12"
    
    if not(x.isdigit()):
       print("this is string")
    if y.isdigit():
       print("this is not string")
    

    输出:

    this is string
    this is not string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-02
      • 2011-03-06
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多