简体   繁体   English

Python:如何添加特定字符作为将列表转换为字符串以区分列表中的最后一项?

[英]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.

相关问题 如何在 python 列表中的最后一个字符串项中添加逗号? - How do I add a comma to the last string item in a list in python? 如何在 Python 的列表值中添加特定字符? - How to add a specific character in a list value in Python? 如何检查python字符串列表在字符串的最后一个字母中是否包含特定字符? - How to check if a python string list contains a specific character in the last letter of a string? 如何在python外部列表的最后一个嵌套列表中添加项目? - How to add an item at the last nested list of an outer list in python? 如何将字符附加到列表中项目的特定部分 - Python - How to append character to specific part of item in list - Python Python〜用字符串列表项替换字符串中的字符 - Python ~ Replace a character in a string with a string list item 替换列表中项目的特定字符 - Python - Replace specific character of item in list - Python 在字符串列表的最后一项之前添加“和” - Add 'and' before the last item in a string list 在 Python 中获取特定列表的最后一次迭代——并且只获取最后一个特定项目 - Grab last iteration of a specific list in Python — and only last specific item 如何在python中替换字符串内特定位置的字母,而不转换为列表? - How to replace a letter in a specific place inside a string in python, without transforming into a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM