📜  Python|替代字符添加

📅  最后修改于: 2022-05-13 01:55:28.491000             🧑  作者: Mango

Python|替代字符添加

有时,在使用Python时,我们可能会遇到需要在 String 中的每个字符之后添加一个字符的问题。这类问题可以在许多日常编程领域中得到应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们迭代每个元素并插入所需的字符。我们擦除最后一个流浪字符。

Python3
# Python3 code to demonstrate working of
# Alternate character addition
# Using loop
 
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = '*'
 
# Alternate character addition
# Using loop
res = ''
for ele in test_str:
    res += ele + K
res = res[:-1]
 
# printing result
print("String after character addition : " + str(res))


Python3
# Python3 code to demonstrate working of
# Alternate character addition
# Using join()
 
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = '*'
 
# Alternate character addition
# Using join()
res = K.join(test_str)
 
# printing result
print("String after character addition : " + str(res))


输出 :
The original string is : geeksforgeeks
String after character addition : g*e*e*k*s*f*o*r*g*e*e*k*s


方法 #2:使用 join()
这是执行此任务的最简单、优雅和推荐的方式。在此,我们只使用一行来执行此任务。 join() 用于执行它。

Python3

# Python3 code to demonstrate working of
# Alternate character addition
# Using join()
 
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = '*'
 
# Alternate character addition
# Using join()
res = K.join(test_str)
 
# printing result
print("String after character addition : " + str(res))
输出 :
The original string is : geeksforgeeks
String after character addition : g*e*e*k*s*f*o*r*g*e*e*k*s