gpt4 book ai didi

python - 用数字来拆分字符串

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:41 24 4
gpt4 key购买 nike

我有这个字符串

a = "IN 744301 Mus Andaman & Nicobar Islands   01  Nicobar 638 Carnicobar 9.2333  92.7833 4"

我想用正则表达式拆分它,无论数字出现在哪里,输出都是这样的

['IN' , '744301', 'Mus Andaman & Nicobar Islands', '01' , 'Nicobar', '638', 'Carnicobar', '9.2333','92.7833', '4' ]

最佳答案

您可以使用前瞻和后视:

import re
a = "IN 744301 Mus Andaman & Nicobar Islands 01 Nicobar 638 Carnicobar 9.2333 92.7833 4"
new_a = re.split('(?<=\d)\s+|\s+(?=\d)', a)

输出:

['IN', '744301', 'Mus Andaman & Nicobar Islands', '01', 'Nicobar', '638', 'Carnicobar', '9.2333', '92.7833', '4']

正则解释:

(?<=\d)\s+ : 匹配前面有数字 ( \s ) 的任何空格 ( \d )。

\s+(?=\d) : 匹配任何后跟数字的空格。

| : 应用具有匹配项的任一连接表达式。

关于python - 用数字来拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56285914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com