I want to transform a list to a string including the square brackets and comma and then concatenate with another string.
JavaScript
x
7
1
Input:
2
list1 = [1, 4, 3, 2, 5]
3
str1 = 'is a list.n'
4
5
Expected output:
6
[1, 4, 3, 2, 5] is a list.
7
What I’m trying is like this:
JavaScript
1
8
1
path = [1, 4, 3, 2, 5]
2
str1 = 'is a list.n'
3
ss = '['
4
for item in path:
5
ss += str(item) + ', '
6
ss += '] ' + str1
7
print(ss)
8
But this results in the following output:
JavaScript
1
2
1
[1, 4, 3, 2, 5, ] is a list.
2
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:
JavaScript
1
11
11
1
path = [1, 4, 3, 2, 5]
2
str1 = 'is a list.n'
3
ss = '['
4
for i in range(len(Path)):
5
if i != (len(path)-1):
6
ss += str(path[i]) + ', '
7
else:
8
ss += str(path[i])
9
ss += '] ' + str1
10
print(ss)
11
A good Approach is using f-Strings.
JavaScript
1
2
1
print(f"{path} is a list.n")
2
if u doesn’t like f-strings then
JavaScript
1
2
1
print("{} is a list.n".format(path))
2