user1761173
user1761173

Reputation: 59

Python search / extract string before and after a character

Need help in extracting string before and after a character using regex in python

string = "My City | August 5"

I would like to extract "My City" and extract "August 5"

string1 = "My City"
string2 = "August 5"

Upvotes: 2

Views: 5279

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174696

Through regex, it would be like

>>> import re
>>> string = "My City | August 5"
>>> string1, string2 = re.split(r'\s+\|\s+', string)
>>> string1
'My City'
>>> string2
'August 5'

\s+ matches one or more space characters, \| matches a literal | symbol . You must need to escape the | in your regex to match a literal | symbol because | pipe is a special meta character in regex which was usually called as alternation operator or logical OR operator.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121416

You don't need a regex here, just use str.partition(), splitting on the | plus the surrounding spaces:

string1, separator, string2 = string.partition(' | ')

Demo:

>>> string = "My City | August 5"
>>> string.partition(' | ')
('My City', ' | ', 'August 5')
>>> string1, separator, string2 = string.partition(' | ')
>>> string1
'My City'
>>> string2
'August 5'

str.partition() splits the string just once; if there are more | characters those are left as part of string2.

If you want to make it a little more robust and handle any number of spaces around the pipe symbol, you can split on just | and use str.strip() to remove arbitrary amounts of whitespace from the start and end of the two strings:

string1, separator, string2 = map(str.strip, string.partition('|'))

Upvotes: 4

jkalden
jkalden

Reputation: 1588

You don't need regular expressions here. Just type

string = "My City | August 5"
string1, string2 = string.split("|")

If you want to crop the trailing space in the results, you can use

string1 = string1.strip(" ")
string2 = string2.strip(" ")

Upvotes: 3

robbintt
robbintt

Reputation: 332

Sure, here's a built in method for splitting a string:

string = "My City | August 5"
delimiter = ' | '  # note the spaces are part of your delimiter
list_of_partial_strings = string.split(delimiter)

There's excellent documentation available for string methods in the Python Standard Library documentation.

Upvotes: 1

Related Questions