在 Python 中打印具有字符串格式的元组

使用格式化的字符串字面量来打印具有字符串格式的元组,例如 print(f’Example tuple: {my_tuple}’)。 格式化字符串文字让我们通过在字符串前加上 f 来在字符串中包含表达式和变量。

my_tuple = ('a', 'b', 'c')

# ✅ format a string with a tuple

result = f'Example tuple: {my_tuple}'
print(result)  # ?️ Example tuple: ('a', 'b', 'c')

# ✅ access specific elements in the tuple

result = f'first: {my_tuple[0]}, second: {my_tuple[1]}, third: {my_tuple[2]}'
print(result)  # ?️ first: a, second: b, third: c

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

# ✅ using the str.format() method

result = 'first: {}, second: {}, third: {}'.format(*my_tuple)
print(result)  # ?️ first: a, second: b, third: c

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

# ✅ print a tuple without the parentheses
result = ','.join(my_tuple)
print(result)  # ?️ 'a,b,c'

在 Python 中打印具有字符串格式的元组

第一个示例使用格式化字符串文字来打印具有字符串格式的元组。

my_tuple = ('a', 'b', 'c')

result = f'Example tuple: {my_tuple}'
print(result)  # 👉️ Example tuple: ('a', 'b', 'c')

格式化字符串文字(f-strings)让我们通过在字符串前面加上 f 来在字符串中包含表达式。

my_str = 'is subscribed:'
my_bool = True

result = f'{my_str} {my_bool}'
print(result)  # 👉️ is subscribed: True

确保将表达式包裹在花括号 – {expression} 中。

我们可以使用括号表示法来访问索引处的元组元素。

my_tuple = ('a', 'b', 'c')


result = f'first: {my_tuple[0]}, second: {my_tuple[1]}, third: {my_tuple[2]}'
print(result)  # 👉️ first: a, second: b, third: c

Python 索引是从零开始的,因此元组中的第一个元素的索引为 0,最后一个元素的索引为 -1 或 len(my_tuple) - 1

或者,我们可以使用 str.format() 方法。

my_tuple = ('a', 'b', 'c')


result = 'Example tuple: {}'.format(my_tuple)
print(result)  # 👉️ Example tuple: ('a', 'b', 'c')

result = 'first: {}, second: {}, third: {}'.format(*my_tuple)
print(result)  # 👉️ first: a, second: b, third: c

str.format() 方法执行字符串格式化操作。

调用该方法的字符串可以包含使用花括号 {} 指定的替换字段。

确保为 format() 方法提供的参数与字符串中的替换字段一样多。

如果我们需要在字符串中访问元组元素,则可以使用可迭代解包运算符在调用 format() 方法时解包元组元素。

my_tuple = ('a', 'b', 'c')


result = 'first: {}, second: {}, third: {}'.format(*my_tuple)
print(result)  # 👉️ first: a, second: b, third: c

* 可迭代解包运算符使我们能够在函数调用、推导式和生成器表达式中解包可迭代对象。

可迭代解包运算符解包元组并将其元素作为多个逗号分隔的参数传递给 str.format() 方法的调用。

如果我们需要打印不带括号的元组,请使用 str.join() 方法。

my_tuple = ('a', 'b', 'c')

result = ','.join(my_tuple)
print(result)  # 👉️ 'a,b,c'

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() 方法的字符串用作元素之间的分隔符。

我们在示例中使用了逗号,但我们可以使用任何其他分隔符,例如 一个空字符串,用于连接不带分隔符的元组元素。