简体   繁体   English

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

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

I have a string value printing in multiple lines.我有一个多行打印的字符串值。 I used three single/double quotes for assigning string value我使用三个单/双引号来分配字符串值

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}')

在此处输入图像描述 It outputs wrong number of characters: 12它输出错误的字符数:12

However, when I assign a string value in one line like但是,当我在一行中分配一个字符串值时

artist = 'Mariah Carey'

I have correct number of characters 11我有正确的字符数 11 在此处输入图像描述

Is it possible to remove all white spaces (leading, middle and trailing) from multi line string value without using regular expressions是否可以在不使用正则表达式的情况下从多行字符串值中删除所有空格(前导、中间和尾随)

str.split() splits a string on whitespace so you could do this: str.split()在空格上分割一个字符串,所以你可以这样做:

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

This will split the string into a list of words.这会将字符串拆分为单词列表。 Those words are then joined with a single space delimiter.然后将这些单词与单个空格分隔符连接起来。

I assumed that you would want to retain one interword space, however, if you want to get rid of all whitespace then join with an empty string:我假设您希望保留一个字间空格,但是,如果您想摆脱所有空格,请使用空字符串连接:

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

Modify your display string:修改你的显示字符串:

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

   Mariah
   Carey
   (full name has 11 characters)

When you use triple quotes and use enter to separate your lines, python inserts \n character which is also added to the total number of characters.当您使用三引号并使用 enter 分隔行时,python 插入\n字符,该字符也添加到字符总数中。 So in the following line所以在下面一行

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

in the replace function instead of a " " use "\n" .在替换 function 而不是" "使用"\n"

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

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