【问题标题】:How to get string and int as input in one line in Python3?如何在 Python3 的一行中获取字符串和 int 作为输入?
【发布时间】:2020-06-19 01:53:33
【问题描述】:

我已经看到下面的link 我的答案,但仍然没有得到预期的答案。

如果我在一行中提供名称和编号,Python 应该将第一个值作为字符串,第二个作为整数。

【问题讨论】:

标签: python python-3.x string input integer


【解决方案1】:
s, num = input("Give str and int :\n").split()
num = int(num)
print(s, type(s))
print(num, type(num))

输出:

Give str and int :
hello 23
hello <class 'str'>
23 <class 'int'>

【讨论】:

  • 它不是一个班轮。
  • 感谢@phoenixo,但是如果不将字符串类型转换为整数值,是否有可能?
  • @MahendrasingJPardeshi 您必须使用类型转换,因为您输入的所有内容都是字符串。
  • 对不起,我认为输入必须是“一行”,而不是代码
【解决方案2】:
a, b = [int(x) if x.isnumeric() else x for x in input().split()]

如果可能,它将转换为输入的任何部分。

【讨论】:

    【解决方案3】:

    如果您确定有一个字符串和一个数字,您可以使用列表推导来获取两者的值。

    x = "Hello 345"
    
    str_value = "".join([s for s in x if s.isalpha()])  # list of alpha characters and join into one string
    num_value = int("".join([n for n in x if n.isdigit()]))  # list of numbers converted into an int
    
    print(str_value)
    >> Hello
    
    print(num_value)
    >> 345
    

    【讨论】:

      【解决方案4】:

      可以使用正则表达式获取字符串和int,如下:

      import re
      
      input_text = "string489234"
      
      re_match = re.match("([^0-9]*) ?([0-9]*)", input_text)
      
      if re_match:
          input_str = re_match.group(1)
          input_int = re_match.group(2)
      

      见:https://docs.python.org/3/library/re.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-10
        相关资源
        最近更新 更多