Split String on Second Occurrence of Character in Python
You can use split()
, join()
, and RegEx functions to split a string on a second occurrence in Python.
The following examples explain how you can split the string based on a second occurrence of a character in Python.
Using split()
and join()
functions
This example explains how to split a string on a second occurrence of a character using the split()
and join()
functions.
Suppose you have the following example string
# example string
x = "ABC_DE_XY_Z"
Split the x
string with a second occurrence of _
character.
# split string on second occurrence of `_` character
"_".join(x.split("_", 2)[:2])
# output
'ABC_DE'
In the above example, we first split the string with _
character into two parts and then again joined the first split
using the _
character.
Using split()
from RegEx
This example explains how to split a string on a second occurrence of a character using the split()
function from re package.
# example String
x = "ABC,DE,XY,Z"
Split the x
string with a second occurrence of ,
character.
# import package
import re
# split string on second occurrence of `,` character
",".join(re.split(",", x, maxsplit=2):2])
In the above example, we used RegEx (re package) to split the string with ,
character into two parts and then again joined the first split
using the ,
character.