Python|在大写字符上拆分字符串的方法
给定一个字符串,编写一个Python程序来拆分大写字符上的字符串。让我们讨论一些解决问题的方法。
方法 #1:使用 re.findall() 方法
Python3
# 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))
Python3
# 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))
Python3
# 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
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))
输出:
Initial String GeeksForGeeks
Resultant prefix ['Geeks', 'For', 'Geeks']
方法 #2:使用 re.split()
Python3
# 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))
输出:
Initial String GeeksForGeeks
Resultant prefix ['Geeks', 'For', 'Geeks']
方法#3:使用枚举
Python3
# 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
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))
输出:
Initial String GeeksForGeeks
Resultant prefix ['Geeks', 'For', 'Geeks']