【问题标题】:How to convert '1,2' into a tuple (1,2) in python?如何在python中将'1,2'转换为元组(1,2)?
【发布时间】:2015-12-25 09:41:33
【问题描述】:

INPUT: '1,2' 这是一个字符串。

OUTPUT: (1,2) 这是一个元组。

如何做到这一点?有什么简单的方法吗?

【问题讨论】:

  • 你做过任何研究吗?看看official Python tutorial,也许?
  • 是的,有一个简单的方法。
  • ast.literal_eval('1,2')

标签: python string type-conversion


【解决方案1】:

不使用地图:

a = '1,2'
print tuple(int(x) for x in list(a.split(',')))

【讨论】:

    【解决方案2】:
    s = '1,2'
    s_tuple = tuple(map(int, s.split(',')))
    

    【讨论】:

      【解决方案3】:
      a = '1,2'
      print tuple(map(int,a.split(',')))
      

      【讨论】:

      • @Petar:感谢您的提及。做出了改变。它现在返回 int
      【解决方案4】:
      def Convert(s):
          p = s.split(",")
          return (int(p[0]), int(p[1]))
      

      【讨论】:

      • 输入是字符串而不是 x, y。
      猜你喜欢
      • 2013-07-25
      • 1970-01-01
      • 2016-01-03
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      相关资源
      最近更新 更多