如何在python中用正则表达式替换一个空格? [英] How to replace just one whitespace with regex in python?
本文介绍了如何在python中用正则表达式替换一个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
T h e t e x t i s w h a t I w a n t t or e p l a c e
我想要这样的结果:
文字是我要替换的
我用 shell、sed 试过了,
echo 'T hetextis W hat I wantreplace e'|sed -r "s/(([a-zA-Z])\s){1}/\2/g"|sed 's/\//G'
成功了.但我不知道如何在 python 中替换它.有人可以帮我吗?
解决方案
如果您只想转换每个字符之间有空格的字符串:
<预><代码>>>>进口重新>>>re.sub(r'(.) ', r'\1', 'T h e t e x t i s wh a t I w a n t to or r e p l c e')'文本是我想要替换的'或者,如果您想删除所有单个空格并将空格替换为一个:
<预><代码>>>>re.sub(r'(?) +', r'\1', 'A B C D')'A B C D'for example:
T h e t e x t i s w h a t I w a n t t o r e p l a c e
I want the result like this:
The text is what I want to replace
I tried that with shell, sed,
echo 'T h e t e x t i s W h a t I w a n t r e p l a c e'|sed -r "s/(([a-zA-Z])\s){1}/\2/g"|sed 's/\ / /g'
it's successfully. but I don't know how to replace this in python. could anybody help me?
解决方案
If you just want to convert a string that has whitespace between each chars:
>>> import re
>>> re.sub(r'(.) ', r'\1', 'T h e t e x t i s w h a t I w a n t t o r e p l a c e')
'The text is what I want to replace'
Or, if you want to remove all single whitespace and replace whitespaces to just one:
>>> re.sub(r'( ?) +', r'\1', 'A B C D')
'AB C D'
这篇关于如何在python中用正则表达式替换一个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文