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

如何在不使用正则表达式的情况下从Python中的多行字符串值中删除空白,python,Python,我有一个字符串值打印在多行。我使用了三个单引号/双引号来分配字符串值 artist = """ Mariah Carey """ name = 'My all' realeased_year = 1997 genre = 'Latin' duration_seconds = 231 print(f'{artist}(full name has {len(artist.strip().r

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

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

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

在空格上拆分字符串,以便执行以下操作:

>>> 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)
在空白处拆分字符串,以便执行以下操作:

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

在替换函数中,而不是使用
使用
“\n”

当使用三重引号和enter分隔行时,python会插入
\n
字符,该字符也会添加到字符总数中。那么在下面的一行中

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

在“替换”功能中,不要使用
使用
”\n“

检查一秒钟……您认为您可以提供完整版本的答案吗?遇到语法错误Thanks@DurdonaA.:在我看来是一个完整的版本。。。我已经从terminal.formatting中剪切并粘贴了逐字记录,{f”“}出现语法错误使用双引号如下:
“”。join()
检查一秒钟……您认为您可以提供完整的答案版本吗?遇到语法错误Thanks@DurdonaA.:在我看来是一个完整的版本。。。我已从terminal.formatting中逐字剪切和粘贴了{f”“}获取语法错误使用双引号如下:
“”。join()
获取错误语法错误:f-string表达式部分不能包含反斜杠如果必须或想要使用f-string,则可以分配
len(artist.strip().replace(“,”)
转换为变量,并在
打印语句中使用该变量。例如,
length=len(artist.strip().replace(“,”)
并在
print(/code>)中使用length。它的工作完全符合问题要求。获取错误语法错误:f-string表达式部分不能包含反斜杠如果必须或想要使用f-string,则可以分配
len(artist.strip().replace(“,”))
转换为变量,并在
打印语句中使用该变量。例如,
length=len(artist.strip()。替换(“,”)
并在
print
中使用length。它完全符合问题要求。如果您尝试使用artist=“Marian Carey”和print(len(artist.strip()))。您将发现相同的12字符长度输出。请再次检查。如果您尝试使用artist=“Marian Carey”并打印(len(artist.strip())。您将发现相同的12字符长度输出。请再查一下。