Python - 在字符串中间添加短语
给定一个字符串,在它中间添加一个短语。
Input : test_str = ‘geekforgeeks is for geeks’, mid_str = “good”
Output : geekforgeeks is good for geeks
Explanation : Added just in middle, after 2 words.
Input : test_str = ‘geekforgeeks best’, mid_str = “is”
Output : geekforgeeks is best
Explanation : Added just in middle, after 1 word.
方法 #1:使用split() +切片+ join()
在这种情况下,字符串被转换为一个单词列表,然后提取中间位置以附加一个新短语。添加后,字符串使用 join() 进行回转换。
Python3
# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
# initializing string
test_str = 'geekforgeeks is for geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing mid string
mid_str = "best"
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 2
# appending in mid
res = temp[:mid_pos] + [mid_str] + temp[mid_pos:]
# conversion back
res = ' '.join(res)
# printing result
print("Formulated String : " + str(res))
Python3
# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
# initializing string
test_str = 'geekforgeeks is for geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing mid string
mid_str = "best"
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 2
# joining and construction using single line
res = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])
# printing result
print("Formulated String : " + str(res))
输出
The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks
方法 #2:使用 split() + 切片 + join() [更紧凑]
和上面的方法类似,只是用one-liner的方式来解决这个问题,为了更紧凑。
蟒蛇3
# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
# initializing string
test_str = 'geekforgeeks is for geeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing mid string
mid_str = "best"
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 2
# joining and construction using single line
res = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])
# printing result
print("Formulated String : " + str(res))
输出
The original string is : geekforgeeks is for geeks
Formulated String : geekforgeeks is best for geeks