Py学习  »  Python

如果字符串中有特殊字符,如何拆分该字符串并将其保留在同一python中?

Heisenberg • 3 年前 • 1211 次点击  

如果字符串中有特殊字符,如何拆分该字符串并将其保留在同一python中?

例如:

输入:

asdf****adec****awd**wer*

所需输出:

['asdf','****','adec','****','awd','**','wer','*']

我的代码:

import re
a=input().strip()
s=re.findall('[*]|\w+', a)
print(s)

我的输出:

['asdf', '*', '*', '*', '*', 'adec', '*', '*', '*', '*', 'awd', '*', '*', 'wer', '*']

我犯了什么错误??我的特殊角色是单独打印的。

有没有不使用模块的方法??

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131147
 
1211 次点击  
文章 [ 3 ]  |  最新文章 3 年前
0stone0
Reply   •   1 楼
0stone0    3 年前

你可以使用正则表达式,比如 (\*+) 具有 re.split .


import re
test='asdf****adec****awd**wer*'

a=test.strip()
s=list(filter(None, re.split(r'([*]+)', a)))
print(s)

将输出:

['asdf', '****', 'adec', '****', 'awd', '**', 'wer', '*']

你可以 try online in this demo


使用 filter

matszwecja
Reply   •   2 楼
matszwecja    3 年前

你只匹配了一个 * 在你的正则表达式中,你需要匹配所有字符,就像你对 \w 加入 + . 在没有模块的情况下需要答案有什么原因吗?

Daweo
Reply   •   3 楼
Daweo    3 年前

对我来说,你的任务更好地由 re.split 而不是 re.findall 认为

import re
text = "asdf****adec****awd**wer*"
parts = re.split(r'(\*+)',text)
print(parts)

输出

['asdf', '****', 'adec', '****', 'awd', '**', 'wer', '*', '']

请注意,我使用捕获的组来通知 重新。分裂 保留分隔符,并且部分中有空字符串,这被认为是最后一个分隔符之后的一部分,如果这是不可接受的,那么就这样做

parts = [p for p in re.split(r'(\*+)',text) if p]

注意:我使用了所谓的原始字符串,以使转义更容易,正如 * 如果你想要文字,它有特殊的意义 * 你必须看到它或把它放进去 [ ] 看见 re 用于讨论使用原始字符串的文档 重新 需要。