用其他char Python替换前导空格

2024-09-21 09:39:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用每个空格的nbsp;替换前导空格。在

所以:

spam --> spam
 eggs -->  eggs
  spam eggs -->   spam eggs

我见过一些使用regex的解决方案,但都是用其他语言编写的。 我在Python中尝试了以下方法,但没有成功。在

^{pr2}$

最后一行似乎最近,但没有雪茄。在

在Python中,用 替换每个前导空格的正确方法是什么?在

如果没有正则表达式,有一个干净的方法可以做到这一点,我很乐意接受,但我自己无法解决。在


Tags: 方法语言spam解决方案eggsregex空格nbsp
3条回答

使用regex模块(在注释中由Wiktor Stribiżew回答)

>>> import regex
>>> line = 'spam'
>>> regex.sub(r'\G\s', ' ', line)
'spam'

>>> line = ' eggs'
>>> regex.sub(r'\G\s', ' ', line)
' eggs'

>>> line = '  spam eggs'
>>> regex.sub(r'\G\s', ' ', line)
'  spam eggs'

根据文档:

\G

A search anchor has been added. It matches at the position where each search started/continued and can be used for contiguous matches or in negative variable-length lookbehinds to limit how far back the lookbehind goes

可以将^{}与回调函数一起使用,并计算匹配的长度:

>>> raw_line = '  spam eggs'
>>> re.sub(r"^\s+", lambda m: " " * len(m.group()), raw_line)
'  spam eggs'

在这里,您甚至不需要昂贵的regex,只需去掉前导空格,并为剥离的字符数准备一些 个字符:

def replace_leading(source, char=" "):
    stripped = source.lstrip()
    return char * (len(source) - len(stripped)) + stripped

print(replace_leading("spam"))         # spam
print(replace_leading(" eggs"))        #  eggs
print(replace_leading("  spam eggs"))  #   spam eggs

相关问题 更多 >

    热门问题