簡體   English   中英

python用字符串之間的特殊字符替換空格

[英]python replace space with special characters between strings

我想用'#'替換字符串之間的所有空格,除了字符串結尾之后的空格。

例:

input=' hello  world    '
output = '#hello##world'

我知道使用rstrip()我可以忽略字符串末尾的空格。 我只想嘗試不使用rstrip()

使用正則表達式。

import re
a = ' hello  world    '
a = re.sub(' +$', '', a)
output = re.sub(' ', '#', a)

但實際上,這更好:

output = re.sub(' ', '#', a.rstrip())

暫無
暫無

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

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