簡體   English   中英

Python 使用多個字符拆分字符串,同時仍保留該字符

[英]Python Split a String using more than one character while still keeping that character

我已經看到許多使用re.split解決方案,但它並沒有解決我的問題。 我希望能夠拆分我的字符串並將某些字符保留在列表中......很難解釋,但這里有一個例子:

文本:

'print("hello world");'

我想要的結果:

["print", "(", "\"", "hello", "world", "\"", ")", ";"]

像 re.split 這樣的事情會給我:

["print", "hello", "world"]

我怎樣才能得到想要的結果?

你可以試試這個。

import re
text='print("hello world");'
parsed=re.findall(r'(\w+|[^a-zA-Z\s])',text)
print(parsed)
#['print', '(', '"', 'hello', 'world', '"', ')', ';']

\\w+ - 捕獲每個單詞。

[^a-zA-Z\\s] - 捕獲不在[a-zA-Z]且不是空格的所有內容。

編輯:當您想捕獲數字和浮點數時,請使用此re表達式\\d+\\.\\d+|\\d+|\\w+|[^a-zA-Z\\s]

\\d+ - 捕獲數字\\d+\\.\\d+ - 捕獲浮點數。

a='print("hello world",[1,2,3,4,3.15]);'
print(re.findall('\d+\.\d+|\d+|\w+|[^a-zA-Z\s]',a)
#['print', '(', '"', 'hello', 'world', '"', ',', '[', '1', ',', '2', ',', '3', ',', '4', ',', '3.15', ']', ')', ';']

嘗試這個:

import re
re.findall(r"[A-Za-z@#]+|\S", 'print("hello world");')

Out[19]: ['print', '(', '"', 'hello', 'world', '"', ')', ';']

暫無
暫無

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

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