Last Updated : 29 Dec, 2024
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:
Python
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)
Let's understand different methods to split and parse a string in Python.
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)
['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)
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')
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4