Python – 避免最后出现的分隔符
给定一个整数列表,使用分隔符执行连接,避免末尾的额外分隔符。
Input : test_list = [4, 7, 8, 3, 2, 1, 9], delim = “*”
Output : 4*7*8*3*2*1*9
Explanation : The rear “*” which usually occurs in concatenation, is avoided.
Input : test_list = [4, 7, 8, 3], delim = “*”
Output : 4*7*8*3
Explanation : The rear “*” which usually occurs in concatenation, is avoided.
方法#1:使用字符串切片
在此,我们使用字符串切片在形成后从字符串中切出最后一个字符。
Python3
# Python3 code to demonstrate working of
# Avoid Last occurrence of delimitter
# Using map() + join() + str()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# appending delim to join
# will leave stray "$" at end
res = ''
for ele in test_list:
res += str(ele) + "$"
# removing last using slicing
res = res[:len(res) - 1]
# printing result
print("The joined string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Avoid Last occurrence of delimitter
# Using map() + join() + str()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# map extends string conversion logic
res = delim.join(map(str, test_list))
# printing result
print("The joined string : " + str(res))
输出
The original list is : [4, 7, 8, 3, 2, 1, 9]
The joined string : 4$7$8$3$2$1$9
方法 #2:使用 map() + join() + str()
在此,我们完全避免使用循环方法来解决这个问题,而使用map() 转换为字符串和join() 来执行连接任务。
Python3
# Python3 code to demonstrate working of
# Avoid Last occurrence of delimitter
# Using map() + join() + str()
# initializing list
test_list = [4, 7, 8, 3, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing delim
delim = "$"
# map extends string conversion logic
res = delim.join(map(str, test_list))
# printing result
print("The joined string : " + str(res))
输出
The original list is : [4, 7, 8, 3, 2, 1, 9]
The joined string : 4$7$8$3$2$1$9