首頁  >  文章  >  後端開發  >  Python怎麼印不帶括號的元組

Python怎麼印不帶括號的元組

WBOY
WBOY轉載
2023-05-16 12:55:061117瀏覽

使用 str.join() 方法列印不帶括號的元組,例如 result = ','.join(my_tuple)。 str.join() 方法將傳回一個包含元組元素的字串,不帶括號,帶有逗號分隔符號。

# ✅ 打印不带括号的字符串元组
tuple_of_str = ('one', 'two', 'three')

result = ','.join(tuple_of_str)
print(result)  # ????️ 'one,two,three'

# -----------------------------------------

# ✅ 打印不带括号的整数元组

tuple_of_int = (1, 2, 3)

result = ','.join(str(item) for item in tuple_of_int)
print(result)  # ????️ '1,2,3'

# -----------------------------------------

# ✅ 打印不带括号和括号的元组列表
list_of_tuples = [(1, 2), (3, 4), (5, 6)]

result = ','.join(','.join(str(item) for item in tup)
                  for tup in list_of_tuples)

print(result)  # ????️ '1,2,3,4,5,6'

Python怎麼印不帶括號的元組

我們使用 str.join() 方法列印不含括號的元組。

str.join() 方法將一個可迭代物件作為參數並傳回一個字串,該字串是可迭代物件中字串的串聯。

請注意 ,如果可迭代物件中有任何非字串值,則該方法會引發 TypeError。

如果我們的元組包含數字或其他類型,請在呼叫 join() 之前將所有值轉換為字串。

tuple_of_int = (1, 2, 3)

result = ','.join(str(item) for item in tuple_of_int)
print(result)  # ????️ '1,2,3'

此範例使用生成器表達式將元組中的每個整數轉換為字串。

生成器表達式用於對每個元素執行一些操作或選擇滿足條件的元素子集。

呼叫 join() 方法的字串用作元素之間的分隔符號。

my_tuple = ('one', 'two', 'three')

my_str = ', '.join(my_tuple)
print(my_str)  # ????️ "one, two, three"

如果我們不需要分隔符號而只想將可迭代的元素連接到字串中,請在空字串上呼叫 join() 方法。

my_tuple = ('one', 'two', 'three')

my_str = ''.join(my_tuple)
print(my_str)  # ????️ "onetwothree"

如果我們需要列印不帶括號並用空格分隔的元組元素,請在包含空格的字串上呼叫 str.join() 方法。

my_tuple = ('one', 'two', 'three')

my_str = ' '.join(my_tuple)
print(my_str)  # ????️ "one two three"

如果我們需要列印不帶括號和括號的元組列表,請使用 2 次呼叫 str.join() 方法。

list_of_tuples = [(1, 2), (3, 4), (5, 6)]

result = ','.join(','.join(str(item) for item in tup)
                  for tup in list_of_tuples)

print(result)  # ????️ '1,2,3,4,5,6'

join() 方法的內部呼叫連接目前迭代的元組的專案。

我們使用 str() 類別將每個數字轉換為字串。

最後一步是使用 join() 方法將清單中的元組連接成帶有逗號分隔符號的字串。

以上是Python怎麼印不帶括號的元組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除