社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python-string.split()但忽略单个空格(例如单词之间)

Matt • 5 年前 • 1624 次点击  

string = 'ABC DEF  GHI JK    LMNO P'

list = string.split()

print(list)

输出:

ABC DEF
GHI JK
LMNO P

.split 在拆分字符串时忽略单个空格?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54603
 
1624 次点击  
文章 [ 3 ]  |  最新文章 5 年前
jws1
Reply   •   1 楼
jws1    5 年前

如果您不想使用regex来执行此操作,那么您可以像以前那样拆分空格并过滤结果。就像这样:

astring = 'ABC DEF  GHI JK    LMNO P'

def strip_spaces(astring):
    temp = astring.split(" ")
    return [element for element in temp if len(element) != 0]

    print(strip_spaces(astring))

# Output: ['ABC', 'DEF', 'GHI', 'JK', 'LMNO', 'P']
DYZ
Reply   •   2 楼
DYZ    5 年前

使用正则表达式拆分两个或多个空格:

import re
re.split("\s{2,}", string)
#['ABC DEF', 'GHI JK', 'LMNO P']
AmphotericLewisAcid
Reply   •   3 楼
AmphotericLewisAcid    5 年前

这就是正则表达式擅长的问题。因此,让我们构造一个正则表达式来查找所有具有多个空格字符的空格。 \s 匹配空格,因此我们继续:

\s

为了匹配正则表达式中的N个或更多的内容,您将 {N,} {2,} 在中匹配2个或更多:

\s{2,}

附带了一个函数,每当正则表达式ping匹配时,该函数都将被拆分。所以,我们要:

import re # This is the built-in regex module
string = "ABC DEF  GHI JK    LMNO P"
my_list = re.split("\s{2,}", string)

list my_list 列表 是Python中的一个内置关键字,您不想重写它。