📜  Python|从字符串中删除初始单词

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

Python|从字符串中删除初始单词

在编程过程中,有时我们会遇到这样一个问题,即要求必须删除字符串中的第一个单词。这类问题很常见,应该了解此类问题的解决方案。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用split()
可以使用split函数执行此任务,该函数执行单词拆分并将字符串的第一个单词与整个单词分开。

# Python3 code to demonstrate working of
# Removing Initial word from string
# Using split()
  
# initializing string 
test_str = "GeeksforGeeks is best"
  
# printing original string 
print("The original string is : " + test_str)
  
# Using split()
# Removing Initial word from string
res = test_str.split(' ', 1)[1]
  
# printing result 
print("The string after omitting first word is : " + str(res))
输出 :
The original string is : GeeksforGeeks is best
The string after omitting first word is : is best

方法 #2:使用partition()
与上述方法中使用的函数相比,分区函数用于在相对较少的内部任务中执行此特定任务。

# Python3 code to demonstrate working of
# Removing Initial word from string
# Using partition()
  
# initializing string 
test_str = "GeeksforGeeks is best"
  
# printing original string 
print("The original string is : " + test_str)
  
# Using partition()
# Removing Initial word from string
res = test_str.partition(' ')[2]
  
# printing result 
print("The string after omitting first word is : " + str(res))
输出 :
The original string is : GeeksforGeeks is best
The string after omitting first word is : is best