Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex split first character

e.g. I have Name : John Frank Smith

What I want is to seperate by first space

so array will be [0]=John [1]=Frank Smith

what I tried, I replace space by ~ and tried to split by regex.

import re
s="John~Frank~Smith"
l=re.compile(r'/~(.+)?/').split(s)

output is:

 ['John~Frank~Smith']

How can I achieve as described above?

first I don't know how to put space in regex.

like image 946
XMen Avatar asked Feb 19 '26 18:02

XMen


2 Answers

Use str.split() with the maxsplit parameter:

>>> s = "John Frank Smith"
>>> s.split(None, 1)
['John', 'Frank Smith']

Note: This will split on multiple occurrences of whitespace, so a string like

John    Frank Smith

would give the same result. If you only want a single space as a separator, use s.split(' ', 1).

like image 146
Niklas B. Avatar answered Feb 23 '26 05:02

Niklas B.


If you want to use a regex:

>>> re.split(r'~', "John~Frank~Smith",1)
['John', 'Frank~Smith']

The ~ are from your example.

like image 41
dawg Avatar answered Feb 23 '26 06:02

dawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!