如何將Python字串轉換為元組?
我們可以透過在字串後面簡單地加上一個逗號 (,) 來將 Python 字串轉換為元組。這將把字串視為元組中的單個元素。這裡我們的字串變數“s”被視為元組中的一個專案,可以透過在字串後面新增逗號來實現。
示例
s = "python"
print("Input string :", s)
t = s,
print('Output tuple:', t)
print(type(t))
輸出
以下是上述程式的輸出
Input string : python
Output tuple: ('python',)
<class 'tuple'>
使用 tuple() 函式
我們還可以使用 tuple() 函式將給定的字串轉換為元組。tuple() 是一個 Python 內建函式,用於從可迭代物件建立元組。
示例
這裡 tuple() 函式假設字串的每個字元都表示一個單獨的專案。
s = "python"
print("Input string :", s)
result = tuple(s)
print('Output tuple:', result)
輸出
Input string : python
Output tuple: ('p', 'y', 't', 'h', 'o', 'n')
使用 string.split() 方法
如果輸入字串具有空格分隔的字元,並且我們只想要這些字元,則可以使用 string.split() 方法來避免將空格計算為元素。
string.split() 方法根據預設分隔符(空格“ ”)或指定的分隔符將給定資料拆分為不同的部分。它返回一個字串元素列表,這些元素根據指定的分隔符進行分隔。
示例
在下面的示例中,具有空格分隔的字元的字串被分割,然後透過使用 string.split() 和 tuple() 函式成功轉換為元組。
s = "a b c d e"
print("Input string :", s)
result = tuple(s.split())
print('Output tuple:', result)
輸出
Input string : a b c d e
Output tuple: ('a', 'b', 'c', 'd', 'e')
示例
在下面的示例中,字串的元素由“@”字元分隔,我們透過指定 s.split(“@”) 來分隔字串的元素,然後將其轉換為元組。
s = "a@b@c@d@e"
print("input string :", s)
result = tuple(s.split("@"))
print('Output tuple:', result)
輸出
input string : a@b@c@d@e
Output tuple: ('a', 'b', 'c', 'd', 'e')
使用 map() 和 int() 函式
如果給定的字串包含以字串形式表示的數字值,則轉換後的元組元素也僅以字串格式表示,如果我們想要轉換元組元素的型別,則需要將 map() 和 int() 函式一起使用。
map(): map 函式用於將給定函式應用於可迭代物件的每個元素。
Int(): int() 函式從給定的字串/數字返回一個轉換後的整數物件。
示例
s = "1 2 3 4 5"
print("Input string :", s)
result = tuple(map(int, s.split(" ")))
print('Output tuple:', result)
print("Type of tuple element: ", type(result[1]))
輸出
Input string : 1 2 3 4 5 Output tuple: (1, 2, 3, 4, 5) Type of tuple element: <class 'int'>
透過使用上述方法,我們可以成功地將 Python 字串轉換為元組。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP