Python - 选择性连续后缀连接
给定一个元素列表,任务是编写一个Python程序,根据每个字符串的后缀来执行连续字符串的连接。
Input : test_list = [“Geeks-“, “for-“, “Geeks”, “is”, “best-“, “for”, “geeks”, suff = ‘-‘
Output : [‘Geeks-for-Geeks’, ‘is’, ‘best-for’, ‘geeks’]
Explanation : Strings are joined to next which have “-” as suffix.
Input : test_list = [“Geeks*”, “for*”, “Geeks”, “is”, “best*”, “for”, “geeks”, suff = ‘*’
Output : [‘Geeks*for*Geeks’, ‘is’, ‘best*for’, ‘geeks’]
Explanation : Strings are joined to next which have “*” as suffix.
方法:使用循环+ endswith() + join()
在这里,我们使用join( ) 执行加入任务,并且endswith()执行对定义的后缀进行条件检查的任务。
Python3
# Python3 code to demonstrate working of
# Selective consecutive Suffix Join
# Using loop + endswith() + join()
# initializing list
test_list = ["Geeks-", "for-", "Geeks", "is",
"best-", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing suffix
suff = '-'
res = []
temp = []
for ele in test_list:
temp.append(ele)
# conditionally test values
if not ele.endswith(suff):
res.append(''.join(temp))
temp = []
if temp:
res.append(''.join(temp))
# printing result
print("The joined result : " + str(res))
输出:
The original list is : [‘Geeks-‘, ‘for-‘, ‘Geeks’, ‘is’, ‘best-‘, ‘for’, ‘geeks’]
The joined result : [‘Geeks-for-Geeks’, ‘is’, ‘best-for’, ‘geeks’]