Python|自定义连续字符配对
有时,在使用Python字符串时,我们可能会遇到需要将连续字符串与分隔符配对的问题。这可以在许多领域中应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用join()
+ 列表推导
上述功能的组合可用于执行此任务。在此,我们使用 join() 执行连接字符的任务,并使用列表推导执行编译。
# Python3 code to demonstrate working of
# Custom Consecutive Character Pairing
# Using join() + list comprehension
import string
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + test_str)
# initializing Delim
delim = '_'
# Custom Consecutive Character Pairing
# Using join() + list comprehension
res = [delim.join(test_str[idx : idx + 2]) for idx in range(len(test_str) - 1)]
# printing result
print("The List of joined Characters : " + str(res))
输出 :
The original string is : geeksforgeeks
The List of joined Characters : ['g_e', 'e_e', 'e_k', 'k_s', 's_f', 'f_o', 'o_r', 'r_g', 'g_e', 'e_e', 'e_k', 'k_s']
方法 #2:使用windowed()
+ 循环
这是解决这个问题的方法之一。在这个形成对的任务中,使用 windowed() 来完成。您需要在外部安装 more_itertools 模块才能执行。
# Python3 code to demonstrate working of
# Custom Consecutive Character Pairing
# Using windowed() + loop
import more_itertools
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + test_str)
# initializing Delim
delim = '_'
# Custom Consecutive Character Pairing
# Using windowed() + loop
res = []
for ele in more_itertools.windowed(test_str, 2):
res.append(ele[0] + delim + ele[1])
# printing result
print("The List of joined Characters : " + str(res))
输出 :
The original string is : geeksforgeeks
The List of joined Characters : ['g_e', 'e_e', 'e_k', 'k_s', 's_f', 'f_o', 'o_r', 'r_g', 'g_e', 'e_e', 'e_k', 'k_s']