Reputation: 21
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?
Upvotes: 0
Views: 3585
Reputation: 13
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)
Upvotes: 0
Reputation: 9047
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
Upvotes: 5