连接 K 周围的字符串的Python程序
给定字符串列表,连接出现在字符串K 周围的所有字符串。
Input : test_list = [“Gfg”, “*”, “is”, “best”, “*”, “love”, “gfg”], K = “*”
Output : [‘Gfg*is’, ‘best*love’, ‘gfg’]
Explanation : All elements around * are joined.
Input : test_list = [“Gfg”, “$”, “is”, “best”, “$”, “love”, “gfg”], K = “$”
Output : [‘Gfg$is’, ‘best$love’, ‘gfg’]
Explanation : All elements around $ are joined.
方法一:使用循环
这是可以执行此任务的粗暴方式。在这里,我们遍历所有元素并检查 K,如果找到,我们将与前一个和后继元素执行所需的连接。
Python3
# Python3 code to demonstrate working of
# Concatenate Strings on K String
# Using loop
# initializing list
test_list = ["Gfg", "+", "is", "best", "+", "love", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K for Concatenate
K = "+"
res = []
idx = 0
while idx < len(test_list):
ele = test_list[idx]
# concatenation if next symbol is K
if (idx < len(test_list) - 1) and test_list[idx + 1] == K:
ele = ele + K + test_list[idx + 2]
# increasing counter by 2
idx += 2
res.append(ele)
idx += 1
# printing result
print("Strings after required concatenation : " + str(res))
Python3
# initializing list
test_list = ["Gfg", "+", "is", "best", "+", "love", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K for Concatenate
K = "+"
# performing split after removing space around K
# splits assuming Strings joined around K
res = ' '.join(test_list).replace(' ' + K + ' ', K).split()
# printing result
print("Strings after required concatenation : " + str(res))
输出
The original list is : ['Gfg', '+', 'is', 'best', '+', 'love', 'gfg']
Strings after required concatenation : ['Gfg+is', 'best+love', 'gfg']
方法 2:使用join() + replace() + split()
以上功能的组合可以解决这个问题。在这种情况下,我们执行所有元素的连接,然后删除目标 K 周围的空间。被视为单个字符串,拆分所需的字符串会产生围绕 K 的连接值。
蟒蛇3
# initializing list
test_list = ["Gfg", "+", "is", "best", "+", "love", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K for Concatenate
K = "+"
# performing split after removing space around K
# splits assuming Strings joined around K
res = ' '.join(test_list).replace(' ' + K + ' ', K).split()
# printing result
print("Strings after required concatenation : " + str(res))
输出
The original list is : ['Gfg', '+', 'is', 'best', '+', 'love', 'gfg']
Strings after required concatenation : ['Gfg+is', 'best+love', 'gfg']