簡體   English   中英

如何使用python re.split拆分字符串但保留數字?

[英]how to use python re.split to split string but keep digits?

我是python學習者。 我想使用python re.split()將字符串拆分為單個字符,但是我不想拆分數字。

Example: s = "100,[+split"
The result should be ["100", ",", "[", "+", "s", "p", "l", "i", "t"]

我嘗試使用re.split(r'[A-Za-z]+|\\d+', s)re.findall(r'[0-9]+]|\\d+', s) ,但是我我真的不擅長使用那些方法。 有人能幫我嗎? 非常感激。

您可以使用re.findall

import re
s = "100,[+split" 
new_s = re.findall('\d+|[a-zA-Z\W]', s)

輸出:

['100', ',', '[', '+', 's', 'p', 'l', 'i', 't']
[re.search('\d*', s).group()] + [val for val in s if not val.isdigit()]

這樣可以為該特定字符串提供所需的輸出,但是在不了解您期望哪種類型的字符串的情況下,很難說它是否在所有情況下都可以使用。

這是通過在字符串中搜索數字,然后將所有非數字字符添加到列表中來實現的。

輸出為:

 ['100', ',', '[', '+', 's', 'p', 'l', 'i', 't']

暫無
暫無

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

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