繁体   English   中英

如果字符串中有特殊字符,如何拆分字符串并将字符串保持在相同的 python 中?

[英]How to split the string if special character in string and keep the string in same python?

如果字符串中有特殊字符,如何拆分字符串并将字符串保持在相同的 python 中?

例如:

输入:

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

需要 Output:

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

我的代码:

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

我的 output:

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

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

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

对我来说,你的任务更适合re.split而不是re.findall ,考虑一下

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

output

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

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

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

注意:我使用所谓的原始字符串来使 escaping 更容易,因为*具有特殊含义,如果您想要文字*您必须将其空格或放入[] 有关使用原始字符串满足re需求的讨论,请参阅re文档。

您在正则表达式中只匹配一个*字符,您需要像使用\w一样通过添加+来匹配所有字符。 需要没有模块的答案背后有什么理由吗?

您可以将(\*+)之类的正则表达式与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', '*']

您可以在此演示中在线试用


使用filter去除列表中的空字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM