Python – Eliminate Capital Letter Starting words from String
Sometimes, while working with Python Strings, we can have a problem in which we need to remove all the words beginning with capital letters. Words that begin with capital letters are proper nouns and their occurrence mean different meaning to the sentence and can be sometimes undesired. Let’s discuss certain ways in which this task can be performed.
Input : test_str = ‘GeeksforGeeks is best for Geeks’
Output : ‘ is best for ‘
Input : test_str = ‘GeeksforGeeks Is Best For Geeks’
Output : ”
Method #1 : Using join() + split() + isupper()
The combination of the above functions can provide one of the ways in which this problem can be solved. In this, we perform the task of extracting individual strings with an upper case using isupper() and then perform join() to get the resultant result.
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)) |
The original string is : GeeksforGeeks is Best for Geeks The filtered string : is for
Method #2 : Using regex()
Using regex is one of the ways in which this problem can be solved. In this, we extract all the elements that are upper case using appropriate 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