簡體   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