Py学习  »  Python

如何使用多个分隔符拆分字符串(Python)

Lorenzo Beronilla • 5 年前 • 1685 次点击  

我正试图进一步分裂一个已经分裂的字符串,以进一步清理和删除不必要的信息位。这是一个由“/”分隔的URL

['https:', '', 'expressjs.com', 'en', 'starter', 'hello-world.html']

我希望能够做到:

['https:', '', 'expressjs','com', 'en', 'starter', 'hello-world','html']

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

L = ['https:', '', 'expressjs.com', 'en', 'starter', 'hello-world.html']
L =  [subitem for item in L for subitem in item.split('.')]

print(L)

输出:

['https:', '', 'expressjs', 'com', 'en', 'starter', 'hello-world', 'html']
Iain Shelvington
Reply   •   2 楼
Iain Shelvington    5 年前

re.split 可以在每个匹配的正则表达式上拆分字符串

>>> re.split('[/\.]', 'https://expressjs.com/en/starter/hello-world.html')
['https:', '', 'expressjs', 'com', 'en', 'starter', 'hello-world', 'html']

[/\.] 匹配任何正斜杠或句点字符