簡體   English   中英

Python:如何在字符串拆分中包含定界符?

[英]Python: How can I include the delimiter(s) in a string split?

我想用多個定界符分割一個字符串,但將定界符保留在結果列表中。 我認為這是第一步,解析任何一種公式都是有用的,而且我懷疑有一個不錯的Python解決方案。

有人在這里用Java問了類似的問題。

例如,典型的拆分如下所示:

>>> s='(twoplusthree)plusfour'
>>> s.split(f, 'plus')
['(two', 'three)', 'four']

但是我正在尋找一種添加加號(或保留它)的好方法:

['(two', 'plus', 'three)', 'plus', 'four']

最終,我想對每個運算符和括號進行此操作,因此,如果有一種獲取方法

['(', 'two', 'plus', 'three', ')', 'plus', 'four']

一勞永逸,那就更好了。

您可以使用Python的re模塊來做到這一點。

import re
s='(twoplusthree)plusfour'
list(filter(None, re.split(r"(plus|[()])", s)))

如果只需要迭代器,則可以省略列表。

import re
s = '(twoplusthree)plusfour'
l = re.split(r"(plus|\(|\))", s)
a = [x for x in l if x != '']
print a

輸出:

['(', 'two', 'plus', 'three', ')', 'plus', 'four']

這是使用re.split的簡單方法:

import re

s = '(twoplusthree)plusfour'
re.split('(plus)',  s)

輸出:

['(two', 'plus', 'three)', 'plus', 'four']

re.splitstring.split非常相似,只不過您傳遞的是正則表達式模式,而不是文字分隔符。 這里的技巧是將()放在模式周圍,以便將其作為一個組提取。

請記住,如果分隔符模式連續兩次出現,則您將有空字符串

這個線程很舊,但是由於它的頂級google結果,我想添加一下:

如果您不想使用正則表達式,則有一種更簡單的方法。 基本上只是調用split,但放回除最后一個標記以外的分隔符

def split_keep_deli(string_to_split, deli):
    result_list = []
    tokens = string_to_split.split(deli)
    for i in xrange(len(tokens) - 1):
        result_list.append(tokens[i] + deli)
    result_list.append(tokens[len(tokens)-1])
    return  result_list

在這里,我在第一次出現字母字符時拆分了一個字符串:

def split_on_first_alpha(i):
    #i="3.5 This is one of the way"
    split_1=re.split(r'[a-z]',i,maxsplit=1, flags=re.IGNORECASE)
    find_starting=re.findall(r'[a-z]',i,flags=re.IGNORECASE)
    split_1[1]=find_starting[0]+split_1[1]
    return split_1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM