Python - 从字符串中消除大写字母开头的单词
有时,在使用Python字符串时,我们可能会遇到需要删除所有以大写字母开头的单词的问题。以大写字母开头的词是专有名词,它们的出现与句子的含义不同,有时可能是不受欢迎的。让我们讨论可以执行此任务的某些方式。
Input : test_str = ‘GeeksforGeeks is best for Geeks’
Output : ‘ is best for ‘
Input : test_str = ‘GeeksforGeeks Is Best For Geeks’
Output : ”
方法 #1:使用 join() + split() + isupper()
上述功能的组合可以提供解决这个问题的方法之一。在此,我们使用 isupper() 执行提取单个大写字符串的任务,然后执行 join() 以获得结果。
Python3
# Python3 code to demonstrate working of
# Eliminate Capital Letter Starting words from String
# Using join() + split() + isupper()
# initializing string
test_str = 'GeeksforGeeks is Best for Geeks'
# printing original string
print("The original string is : " + str(test_str))
# Eliminate Capital Letter Starting words from String
# Using join() + split() + isupper()
temp = test_str.split()
res = " ".join([ele for ele in temp if not ele[0].isupper()])
# printing result
print("The filtered string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Eliminate Capital Letter Starting words from String
# Using regex()
import re
# initializing string
test_str = 'GeeksforGeeks is Best for Geeks'
# printing original string
print("The original string is : " + str(test_str))
# Eliminate Capital Letter Starting words from String
# Using regex()
res = re.sub(r"\s*[A-Z]\w*\s*", " ", test_str).strip()
# printing result
print("The filtered string : " + str(res))
输出 :
The original string is : GeeksforGeeks is Best for Geeks
The filtered string : is for
方法 #2:使用 regex()
使用正则表达式是解决此问题的方法之一。在此,我们使用适当的正则表达式提取所有大写的元素。
Python3
# Python3 code to demonstrate working of
# Eliminate Capital Letter Starting words from String
# Using regex()
import re
# initializing string
test_str = 'GeeksforGeeks is Best for Geeks'
# printing original string
print("The original string is : " + str(test_str))
# Eliminate Capital Letter Starting words from String
# Using regex()
res = re.sub(r"\s*[A-Z]\w*\s*", " ", test_str).strip()
# printing result
print("The filtered string : " + str(res))
输出 :
The original string is : GeeksforGeeks is Best for Geeks
The filtered string : is for