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:
[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!
Advertisement
Answer
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.
print(f"{path} is a list.n")
if u doesn’t like f-strings then
print("{} is a list.n".format(path))