Python:用一个空格替换双空格,并删除单空格
我想更改如下字符串:Python:用一个空格替换双空格,并删除单空格,python,string,Python,String,我想更改如下字符串: T h i s i s a t e s t 致: 这是我的代码,有效 while ' ' in s: s = s.replace(' ', '$$') while ' ' in s: s = s.replace(' ', '') while '$$' in s: s = s.replace('$$', ' ') 但是,有没有简单的解决办法 对于删除所有空格或删除单个空格并保留
T h i s i s a t e s t
致:
这是我的代码,有效
while ' ' in s:
s = s.replace(' ', '$$')
while ' ' in s:
s = s.replace(' ', '')
while '$$' in s:
s = s.replace('$$', ' ')
但是,有没有简单的解决办法
对于删除所有空格或删除单个空格并保留多个空格,也有类似的解决方案,但在我的情况下,我也必须用单个空格替换双空格。:
输出:
这应该行得通
说明:
'This is a test'
您可以在re中使用负前瞻:
import re
s = 'T h i s a t e s t'
t = re.sub(r' (?! )', '', s)
print(t)
如期而至
这是一个测试
实际上,它为每个空间序列删除一个空间:
>>> t= 'T h i s i s a t e s t'
>>> re.sub(r' (?! )', '', t)
'This is a test'
您如何知道要包含哪些空间以及要排除哪些空间?绳子可以是任何东西!示例代码中的
while
循环可能重复,因为不带第三个参数的str.replace
将用第二个参数字符串替换字符串中所有指定的(第一个参数)子字符串。因此,您可以在一行中执行相同的操作:s=s.replace('''$').replace('''$').replace(''$').replace('$$,'')
。它本身就是一个非常简单的解决方案,不过你不应该担心如果字符串中还有$chars,它就会失败。它不会删除单个空格@艾哈迈德现在离开我的办公桌,明天将添加一个不同案例的修复,干杯,但它保持双倍spaces@Ahmad它应该从每个空格序列中删除一个空格。它应该删除字母后面的每个空格
s="T h i s i s a t e s t"
s=" ".join([str(i).replace(" ","") for i in s.split(" ")])
s = 'T h i s i s a t e s t'
''.join([row[0] for row in zip(s, range(len(s)+1)) if row[1]%2==0])
'This is a test'
import re
s = 'T h i s a t e s t'
t = re.sub(r' (?! )', '', s)
print(t)
>>> t= 'T h i s i s a t e s t'
>>> re.sub(r' (?! )', '', t)
'This is a test'