Python|在每个字符对之后插入字符
有时,我们可能会遇到需要在 pair(second) 字符之后插入特定字符的问题。在处理数据时可能会出现此类问题,这些数据需要插入逗号或任何其他主要在机器学习领域中的特殊字符。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用join()
+ 列表推导
上述方法的组合可用于执行此特定任务。列表理解和切片可用于将字符串转换为列表,连接函数可用于重新加入它们,在它们之间插入所需的字符。
# Python3 code to demonstrate working of
# Insert character after every character pair
# Using join() + list comprehension
# initializing string
test_str = "GeeksforGeeks"
# printing original string
print("The original string is : " + test_str)
# Using join() + list comprehension
# Insert character after every character pair
res = ', '.join(test_str[i:i + 2] for i in range(0, len(test_str), 2))
# printing result
print("The string after inserting comma after every character pair : " + res)
输出 :
The original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek, s
方法 #2:使用zip() + join()
上述功能的组合可用于执行此特定任务。其中,zip函数将字符转换为可迭代的元组,split函数用于分隔奇偶字符。然后列表推导负责将元组转换为字符串列表,最后使用 join函数将结果连接起来。
# Python3 code to demonstrate working of
# Insert character after every character pair
# Using zip() + join()
# initializing string
test_str = "GeeksforGeeks"
# printing original string
print("The original string is : " + test_str)
# Using zip() + join()
# Insert character after every character pair
res = ', '.join(a + b for a, b in zip(test_str[::2], test_str[1::2]))
# printing result
print("The string after inserting comma after every character pair : " + res)
输出 :
The original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek