使用 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怎么打印不带括号的元组-LMLPHP

我们使用 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怎么打印不带括号的元组的详细内容,更多请关注Work网其它相关文章!

09-16 01:00