Python | Ways to split strings on Uppercase characters
Given a string, write a Python program to split strings on Uppercase characters. Let’s discuss a few methods to solve the problem.
Method #1: Using re.findall() method
# Python code to demonstrate # to split strings # on uppercase letter import re # Initialising string ini_str = 'GeeksForGeeks' # Printing Initial string print ( "Initial String" , ini_str) # Splitting on UpperCase using re res_list = [] res_list = re.findall( '[A-Z][^A-Z]*' , ini_str) # Printing result print ( "Resultant prefix" , str (res_list)) |
chevron_right
filter_none
Output:
Initial String GeeksForGeeks Resultant prefix ['Geeks', 'For', 'Geeks']
Method #2: Using re.split()
# Python code to demonstrate # to split strings # on uppercase letter import re # Initialising string ini_str = 'GeeksForGeeks' # Printing Initial string print ( "Initial String" , ini_str) # Splitting on UpperCase using re res_list = [s for s in re.split( "([A-Z][^A-Z]*)" , ini_str) if s] # Printing result print ( "Resultant prefix" , str (res_list)) |
chevron_right
filter_none
Output:
Initial String GeeksForGeeks Resultant prefix ['Geeks', 'For', 'Geeks']
Method #3: Using enumerate
# Python code to demonstrate # to split strings # on uppercase letter # Initialising string ini_str = 'GeeksForGeeks' # Printing Initial string print ( "Initial String" , ini_str) # Splitting on UpperCase using re res_pos = [i for i, e in enumerate (ini_str + 'A' ) if e.isupper()] res_list = [ini_str[res_pos[j]:res_pos[j + 1 ]] for j in range ( len (res_pos) - 1 )] # Printing result print ( "Resultant prefix" , str (res_list)) |
chevron_right
filter_none
Output:
Initial String GeeksForGeeks Resultant prefix ['Geeks', 'For', 'Geeks']
Recommended Posts:
- Python | Ways to split strings using newline delimiter
- Python | Pandas Split strings into two List/Columns using str.split()
- Python | Ways to split a string in different ways
- Python | Split multiple characters from string
- Python | Split string into list of characters
- Python | Split string in groups of n consecutive characters
- Python | Split Sublist Strings
- Python | Reversed Split Strings
- Python | Split strings in list with same prefix in all elements
- Python | Split strings and digits from string list
- Python | Split CamelCase string to individual strings
- Python | Split list of strings into sublists based on length
- Python | Pandas Reverse split strings into two List/Columns using str.rsplit()
- Python | Ways to check string contain all same characters
- Ways to print escape characters in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.