简体   繁体   中英

Why does python puts a space in front of my formatted string

I have started to learn python recently and found it very fascinating. However when I try formatted strings, f"{var}..." I got a redundant space in front of it.

This is my code:

# Formatted Strings
segment1 = "First segment"
segment2 = "Second segment"
notFormatted = "First: " + segment1 + " Second: " + segment2 + "\n"  # This is hard to read / maintain
formatted = f"First: {segment1} Second: {segment2} \n"  # This approach is much cleaner
print(notFormatted, formatted)  # Should output same text

What I got: [In console]

First: First segment Second: Second segment
 First: First segment Second: Second segment 

As shown above the the second line starts with a space and ends with a space I know I can use the strip function to remove it but I am curious why is it there.Is it because the \n ?


Update:

# Formatted Strings
segment1 = "First segment"
segment2 = "Second segment"
notFormatted = "First: " + segment1 + " Second: " + segment2 + "\n".strip()  # This is hard to read / maintain
formatted = f"First: {segment1} Second: {segment2} \n".strip()  # This approach is much cleaner
print(notFormatted, formatted)  # Should output same text

This code's out put merges two lines together so how should I solve this?

As mentioned in python doc , print function as--

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

So print function takes a default separator of ' ' , that is why you are getting extra space. You can remove it by

print(notFormatted, formatted, sep='')  # Should output same text

output

First: First segment Second: Second segment
First: First segment Second: Second segment 

it is because the , in the print(notFormatted,formatted) puts a space between the two printed things. and since your notFormatted has a \n at the end, and then python puts the space, your printed lines have a space after the new line.

Try this instead: print(notFormatted + formatted)

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