如何將 Python 元組轉換為字串?
元組是物件的集合,這些物件是有序且不可變的。元組是序列,就像列表一樣。元組和列表之間的區別在於,元組不能像列表那樣更改,並且元組使用圓括號,而列表使用方括號。我們可以透過三種不同的方式將 Python 元組轉換為字串。
使用 for 迴圈。
使用 Python 的 join() 方法
使用 functool.reduce() 方法
使用 for 迴圈
在 Python 中,我們可以使用 for 迴圈輕鬆迭代元組元素,然後我們將每個元素追加/新增到字串物件中。在下面的示例中,我們將看到如何將元組轉換為字串。
示例
為了避免在連線時出現 TypeError,我們在新增到字串之前更改了迴圈元素的型別。
t = ('p', 'y', 't', 'h', 'o', 'n', ' ', 3, '.', 10, '.', 0 ) print("Input tuple: ", t) print(type(t)) s = '' # crete en empty string for ele in t: s += str(ele) print("String Output: ", s) print(type(s))
輸出
Input tuple: ('p', 'y', 't', 'h', 'o', 'n', ' ', 3, '.', 10, '.', 0) <class 'tuple'> String Output: python 3.10.0 <class 'str'>
使用 Python 的 join() 方法
要將 Python 元組轉換為字串,我們將使用 join() 方法。join() 是 Python 字串方法,它以元組等可迭代物件作為引數,並返回使用字串分隔符或定界符連線的 Python 字串。
語法
str.join(iterable)
示例
讓我們舉個例子,將 Python 元組轉換為字串。
t = ('p', 'y', 't', 'h', 'o', 'n' ) print("Input tuple: ", t) print(type(t)) output = "".join(t) print("String Output: ", output) print(type(output))
輸出
Input tuple: ('p', 'y', 't', 'h', 'o', 'n') <class 'tuple'> String Output: python <class 'str'>
示例
如果我們將 join() 方法應用於包含混合資料型別(字串、浮點數和整數)的元組,則 join() 方法將引發 TypeError。為了避免此錯誤,我們需要將所有元組元素轉換為字串資料型別。
t = ('p', 'y', 't', 'h', 'o', 'n', ' ', 3.10, '.', 0 ) print("Input tuple: ", t) print(type(t)) output = "".join(map(str,t)) print("String Output: ", output) print(type(output))
輸出
Input tuple: ('p', 'y', 't', 'h', 'o', 'n', ' ', 3.1, '.', 0) <class 'tuple'> String Output: python 3.1.0 <class 'str'>
透過使用 map() 函式,我們首先將所有元組元素轉換為字串資料型別。然後將其傳遞給 join 方法。
使用 functool.reduce() 方法
reduce() 函式在 functool 模組中可用,它將函式作為其第一個引數,將可迭代物件作為其第二個引數。
語法
functools.reduce(function, iterable[, initializer])
示例
import functools import operator t = ('p', 'y', 't', 'h', 'o', 'n' ) print("Input tuple: ", t) print(type(t)) output = functools.reduce(operator.add, t) print("String Output: ", output) print(type(output))
輸出
Input tuple: ('p', 'y', 't', 'h', 'o', 'n') class 'tuple'> String Output: python <class 'str'>
我們必須匯入兩個 Python 模組 **funtools** 和 **operator** 以使用 reduce() 和 add() 函式將元組轉換為字串。
廣告