【问题标题】:How to get integer for two characters in python如何在python中获取两个字符的整数
【发布时间】:2022-06-22 22:09:45
【问题描述】:
a = "a26lsdm3684"

如何获得值为 26 的整数(a[1] 和 a[2])?如果我写 int(a[1) 或 int (a[2]) 它只会给我一个字符的整数。当我想要值为 26 的整数并将其存储在变量 b 中时,我应该写什么?

【问题讨论】:

  • 使用加号+ 运算符?
  • int(a[1:3]) 或许?

标签: python


【解决方案1】:

切出两个字符,然后转换:

b = int(a[1:3])  # Slices are exclusive on the end index, so you need to go to 3 to get 1 and 2

【讨论】:

    【解决方案2】:

    只要您知道确切的索引,您就可以从字符串中获取子字符串并将其转换为 int

    a = "a26lsdm3684"
    
    substring_of_a = a[1:3]
    number = int(substring_of_a)
    
    print(number, type(number))
    

    【讨论】:

      【解决方案3】:

      有不止一种方法可以做到这一点。

      import re
      
      a = "a26lsdm3684"
      
      print(int(a[1:3]))
      print(int((re.findall(r'\d+', a))[0]))
      print(int((re.split(r'\D+', a))[1]))
      # 26
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-05
        • 1970-01-01
        • 2016-01-29
        • 2021-05-30
        • 1970-01-01
        • 2022-09-28
        相关资源
        最近更新 更多