簡體   English   中英

Python 將元組轉換為字符串

[英]Python convert tuple to string

我有一個這樣的字符元組:

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

如何將其轉換為字符串,使其類似於:

'abcdgxre'

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

>>>

這是一種使用join的簡單方法。

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

這有效:

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

最簡單的方法是使用這樣的連接:

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

這是有效的,因為你的分隔符基本上沒有,甚至不是空格:''。

如果只是將str()用於元組,如下所示:

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

print(t, type(t))

s = str(t) # Here

print(s, type(s))

只有類型可以從tuple更改為str而無需更改值,如下所示:

('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') <class 'tuple'>
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') <class 'str'>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM