繁体   English   中英

如何在不使用正则表达式的情况下从 Python 中的多行字符串值中删除空格

[英]How to remove white space from multi line string value in Python without using regular expression

我有一个多行打印的字符串值。 我使用三个单/双引号来分配字符串值

artist = """
       Mariah
       Carey
       """
 name = 'My all'
 realeased_year = 1997
 genre = 'Latin'
 duration_seconds = 231

print(f'{artist}(full name has {len(artist.strip().replace(" ", ""))} characters) and her song \'{name}\' was released in {realeased_year + 1}')

在此处输入图像描述 它输出错误的字符数:12

但是,当我在一行中分配一个字符串值时

artist = 'Mariah Carey'

我有正确的字符数 11 在此处输入图像描述

是否可以在不使用正则表达式的情况下从多行字符串值中删除所有空格(前导、中间和尾随)

str.split()在空格上分割一个字符串,所以你可以这样做:

>>> artist = """
...        Mariah
...        Carey
...        """
>>> ' '.join(artist.split())
'Mariah Carey'

这会将字符串拆分为单词列表。 然后将这些单词与单个空格分隔符连接起来。

我假设您希望保留一个字间空格,但是,如果您想摆脱所有空格,请使用空字符串连接:

>>> ''.join(artist.split())
'MariahCarey'

修改你的显示字符串:

>>> print(f'{artist}(full name has {len("".join(artist.split()))} characters)')

   Mariah
   Carey
   (full name has 11 characters)

当您使用三引号并使用 enter 分隔行时,python 插入\n字符,该字符也添加到字符总数中。 所以在下面一行

print(f'{artist}(full name has {len(artist.strip().replace(" ", ""))} characters) and her song \'{name}\' was released in {realeased_year + 1}')

在替换 function 而不是" "使用"\n"

暂无
暂无

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

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