📜  Python – 通过分隔符连接元组元素

📅  最后修改于: 2022-05-13 01:55:32.723000             🧑  作者: Mango

Python – 通过分隔符连接元组元素

给定一个元组,通过分隔符连接元组的每个元素。

方法#1:使用列表推导

在此,我们使用列表理解中的循环迭代元组中的每个元素,并使用 +运算符连接。

Python3
# Python3 code to demonstrate working of 
# Concatenate Tuple elements by delimiter
# Using list comprehension
  
# initializing tuple
test_tup = ("Gfg", "is", 4, "Best")
  
# printing original tuple
print("The original tuple is : " + str(test_tup))
  
# initializing delim 
delim = "-"
  
# using str() to convert elements to string 
# join to convert to string
res = ''.join([str(ele) + delim for ele in test_tup])
  
# striping stray char 
res = res[ : len(res) - len(delim)]
  
# printing result 
print("Concatenated Tuple : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Concatenate Tuple elements by delimiter
# Using join() + map()
  
# initializing tuple
test_tup = ("Gfg", "is", 4, "Best")
  
# printing original tuple
print("The original tuple is : " + str(test_tup))
  
# initializing delim 
delim = "-"
  
# for joining, delim is used 
res = delim.join(map(str, test_tup))
  
# printing result 
print("Concatenated Tuple : " + str(res))


输出
The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best

方法 #2:使用 join() + map()

在此,我们使用 str() 将所有字符转换为字符串并映射以对所有元素执行 str(),然后使用 join() 连接。

Python3

# Python3 code to demonstrate working of 
# Concatenate Tuple elements by delimiter
# Using join() + map()
  
# initializing tuple
test_tup = ("Gfg", "is", 4, "Best")
  
# printing original tuple
print("The original tuple is : " + str(test_tup))
  
# initializing delim 
delim = "-"
  
# for joining, delim is used 
res = delim.join(map(str, test_tup))
  
# printing result 
print("Concatenated Tuple : " + str(res)) 
输出
The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best