简体   繁体   中英

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

However, when I assign a string value in one line like

artist = 'Mariah Carey'

I have correct number of characters 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:

>>> 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. 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" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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