Python将元组转换为字符串

int*_*el3 85 python string tuples

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

('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
Run Code Online (Sandbox Code Playgroud)

如何将其转换为字符串,使其如下所示:

'abcdgxre'
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 139

用途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.

>>>
Run Code Online (Sandbox Code Playgroud)

  • 对于数字,您可以尝试:`''.join(map(str,tup))` (48认同)
  • 如果元组包含数字,则不起作用.尝试tup =(3,无,无,无,无,1406836313736) (20认同)

Bac*_*ics 24

这是一种使用join的简单方法.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
Run Code Online (Sandbox Code Playgroud)


Tru*_*ker 10

这有效:

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
Run Code Online (Sandbox Code Playgroud)

它会产生:

'abcdgxre'
Run Code Online (Sandbox Code Playgroud)

您还可以使用逗号分隔符来生成:

'a,b,c,d,g,x,r,e'
Run Code Online (Sandbox Code Playgroud)

通过使用:

','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
Run Code Online (Sandbox Code Playgroud)