将一个元素元组(int)转换为str

ruh*_*ruh -1 python string tuples

假设一个元组有一个整数:

tup = (19201,)
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种获得此输出的方法:

tup = "(19201)"
Run Code Online (Sandbox Code Playgroud)

到目前为止,我试过这个:

str_tup = "(" + tup[0] + ")"
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误:

TypeError:无法隐式地将'int'对象转换为str

Kon*_*lph 6

比串联更好的方法是使用Python的格式化语法:

str_tup = '({})'.format(tup[0])
Run Code Online (Sandbox Code Playgroud)

str.format将替换{}你给它的参数(这里:你的元组值).

更好的是,你可以将它推广到更高级别的元组:

str_tup = '({})'.format(', '.join([str(x) for x in tup]))
Run Code Online (Sandbox Code Playgroud)

这使用Python的列表推导语法将所有元组元素转换为字符串,然后使用join连接字符串连接它们.