Split and Parse a string in Python
In this article, we'll look at different ways to split and parse strings in Python. Let's understand this with the help of a basic example:
s = "geeks,for,geeks"
# Split the string by commas
res = s.split(',')
# Parse the list and print each element
for item in res:
print(item)
Output
geeks for geeks
Let's understand different methods to split and parse a string in Python.
Table of Content
Using re.split()
re.split()
uses regular expressions to split a string based on patterns, making it highly flexible for complex cases with multiple delimiters.
import re
# Given string
s = "geeks;for,geeks"
# Split `s` at ';', ',', or space
res= re.split(r'[;, ]',s)
# Parse and print each item
for item in res:
print(item)
Output
['geeks', 'for', 'geeks']
Using map()
We can use the map()
function to split a string into parts and then change each part, like turning all words into uppercase. It helps us process each piece of the string easily.
s = "geeks,for,geeks"
# Split and convert each item to uppercase using map
res = list(map(str.upper, s.split(',')))
# Print each item
for item in res:
print(item)
Output
GEEKS FOR GEEKS
Using partition
partition()
method splits a string into three parts. Part before the first delimiter, the delimiter itself, and the part after it. It’s useful when we only need to split at the first occurrence of a specific character.
s = "geeks,for,geeks"
# Split at the first comma using partition
a, _, b = s.partition(',')
print(a) # Part before the first comma ('geeks')
print(b) # Part after the first comma ('for,geeks')
Output
geeks for,geeks