【问题标题】:Python convert tuple to stringPython将元组转换为字符串
【发布时间】:2013-11-07 15:01:01
【问题描述】:

我有一个这样的字符元组:

('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')

如何将其转换为字符串,使其类似于:

'abcdgxre'

【问题讨论】:

  • 也试试这个reduce(add, ('a', 'b', 'c', 'd'))
  • 在这个例子中@GrijeshChauhan 中的add 是什么?
  • @Steve 你需要从operator 模块导入add 函数。顺便说一句 "".join 更适合这里,但如果你想添加不同类型的对象,你可以使用 add Check this working example

标签: python string tuples


【解决方案1】:

使用str.join:

>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

>>>

【讨论】:

  • 如果元组包含数字则不起作用。试试 tup = (3, None, None, None, None, 1406836313736)
  • 对于数字,你可以试试这个:''.join(map(str, tup))
  • 数字和无请尝试''.join(map(lambda x: str(x or ''), (None, 1, 2, 'apple')))
【解决方案2】:

这是一个使用 join 的简单方法。

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

【讨论】:

    【解决方案3】:

    这行得通:

    ''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
    

    它会产生:

    'abcdgxre'
    

    您也可以使用逗号之类的分隔符来生成:

    'a,b,c,d,g,x,r,e'
    

    通过使用:

    ','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
    

    【讨论】:

      【解决方案4】:

      最简单的方法是像这样使用连接:

      >>> myTuple = ['h','e','l','l','o']
      >>> ''.join(myTuple)
      'hello'
      

      这是有效的,因为您的分隔符本质上什么都不是,甚至不是空格:''。

      【讨论】:

      • 你的“myTuple”是一个列表顺便说一句
      猜你喜欢
      • 2021-05-30
      • 2012-03-15
      • 2023-01-10
      • 2022-07-24
      • 1970-01-01
      • 2019-07-28
      • 2018-11-11
      • 2011-03-18
      • 2011-05-16
      相关资源
      最近更新 更多