Python 打印不带括号的元组
使用 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'
我们使用 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()
方法将列表中的元组连接成带有逗号分隔符的字符串。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。