[英]Python: How to add specific character as transforming a list to a string in differentiating the last item in the list?
I want to transform a list to a string including the square brackets and comma and then concatenate with another string.我想将列表转换为包含方括号和逗号的字符串,然后与另一个字符串连接。
Input:
list1 = [1, 4, 3, 2, 5]
str1 = 'is a list.\n'
Expected output:
[1, 4, 3, 2, 5] is a list.
What I'm trying is like this:我正在尝试的是这样的:
path = [1, 4, 3, 2, 5]
str1 = 'is a list.\n'
ss = '['
for item in path:
ss += str(item) + ', '
ss += '] ' + str1
print(ss)
But this results in the following output:但这会导致以下 output:
[1, 4, 3, 2, 5, ] is a list.
How to prevent the last comma ',' from generating as the process of transform?如何防止最后一个逗号','作为转换过程生成?
I'm considering to take a specific process based on whether the item is the last one in the list.我正在考虑根据该项目是否是列表中的最后一项来采取特定流程。
But how can I know it?但是我怎么知道呢?
Or else is there any other solution?或者还有其他解决方案吗?
Really appreciate!非常感谢!
Print function uses the __str__
or __repr__
magic method of objects to render them. Print function 使用对象的
__str__
或__repr__
魔术方法来渲染它们。 Knowing that you can do either:知道您可以执行以下任一操作:
print(path, "is a list.")
Or with string formatting:或使用字符串格式:
print(f"{path} is a list.")
This is bad Approah:这是不好的方法:
path = [1, 4, 3, 2, 5]
str1 = 'is a list.\n'
ss = '['
for i in range(len(Path)):
if i != (len(path)-1):
ss += str(path[i]) + ', '
else:
ss += str(path[i])
ss += '] ' + str1
print(ss)
A good Approach is using f-Strings.一个好的方法是使用 f-Strings。
print(f"{path} is a list.\n")
if u doesn't like f-strings then如果你不喜欢 f-strings 那么
print("{} is a list.\n".format(path))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.