Python将元组转换为字符串

2024-04-25 10:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组这样的字符:

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

如何将其转换为字符串,使其像:

'abcdgxre'

Tags: 字符串字符abcdgxre
3条回答

使用^{}

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

>>>

这是有效的:

''.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'))

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

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

相关问题 更多 >