Python - 将单词移动到后端
有时,在使用Python字符串时,我们可能会遇到需要找到一个单词并将其移动到字符串末尾的问题。这可以应用于许多领域,包括日间编程和学校编程。让我们讨论可以执行此任务的某些方式。
方法 #1:使用replace() + "+" operator
上述功能的组合可用于执行此任务。在此,我们用空字符串替换元素并将工作附加到字符串的末尾以执行此任务。
# Python3 code to demonstrate working of
# Move Word to Rear end
# Using replace() + "+" operator
# initializing string
test_str = 'Geeksforgeeks is best for geeks '
# printing original string
print("The original string is : " + str(test_str))
# initializing Substring
sub_str = 'best'
# Move Word to Rear end
# Using replace() + "+" operator
res = test_str.replace(sub_str, "") + str(sub_str)
# printing result
print("The string after word removal : " + str(res))
输出 :
The original string is : Geeksforgeeks is best for geeks
The string after word removal : Geeksforgeeks is for geeks best
方法 #2:使用字符串切片和find()
上述功能的组合也可用于执行此任务。在此,我们构造字符串列表并在使用 find() 执行移动和切片后再次加入它。
# Python3 code to demonstrate working of
# Move Word to Rear end
# Using string slicing and find()
# initializing string
test_str = 'Geeksforgeeks is best for geeks '
# printing original string
print("The original string is : " + str(test_str))
# initializing Substring
sub_str = 'best'
# Move Word to Rear end
# Using string slicing and find()
res = test_str[:test_str.find(sub_str)] + test_str[test_str.find(sub_str) + len(sub_str):] + sub_str
# printing result
print("The string after word removal : " + str(res))
输出 :
The original string is : Geeksforgeeks is best for geeks
The string after word removal : Geeksforgeeks is for geeks best