简体   繁体   English

python正则表达式拆分第一个字符

[英]python regex split first character

eg I have Name : John Frank Smith 我有名字: 约翰弗兰克史密斯

What I want is to seperate by first space 我想要的是通过第一空间分开

so array will be [0]=John [1]=Frank Smith 所以数组将是[0] =约翰[1] =弗兰克史密斯

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. 首先我不知道如何在正则表达式中放置空格。

Use str.split() with the maxsplit parameter: str.split()maxsplit参数一起使用:

>>> 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) . 如果您只想要一个空格作为分隔符,请使用s.split(' ', 1)

If you want to use a regex: 如果你想使用正则表达式:

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

The ~ are from your example. ~来自你的榜样。

no need for regex, use split() : 不需要正则表达式,使用split():

s="John~Frank~Smith"
s.split('~',1)

['John', 'Frank~Smith']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM