Print multiple newlines with a text in it using only one print statement

Hello, I’d like to know how do you print multiple new lines with text in it using only one print statement. I have seen a solution of doing it in this way, print("\n" * <NUMBER>), but not a single solution I’ve found mentioning you can do that in a single print statement with strings in it. The result I’d like to achieve is something like this:

my_str = "Hi"

print(f"\n{my_str}" * 3)

where the new lines are printed three times instead of the strings.

EDIT: I just realized I could just write it as,

my_str = "\n" * 3

print(f"{my_str}Hi")

though I’m still curious if I could write it into one print statement instead of declaring a variable to perform that task.

Not sure if this is what you’re looking for? Meaning, we can substitute the {my_str} variable} directly with "\n" * 3 , then remove the f-string format and concatenate with "Hi"

print("\n" * 3 + "Hi")

Output:



Hi

1 Like

Hello and thank you for replying to my question :smiley:

Yes, that does work, but is there a way to do that without excluding the f-string format? I tried using escape characters, couldn’t figure out or that it just won’t work that way. If not, then I’ll just stick to declaring a variable for doing that work only or concatenate it as seen in your solution.

See:
Python doc on f-strings

image

2 Likes

This depends a little on whether you want to repeat a particular string or whether you simply want your print statement to produce extra lines. It’s viewing the docs on print- https://docs.python.org/3/library/functions.html#print and noting that there is an end parameter that defaults to "\n" which is why all print statements have a new line even if the string doesn’t. If you wanted to print a string and then dump lots of new lines you could pass an argument to end instead of modifying the string itself, for example-

print(mystr, end="\n\n")
print(f"whatever string i want {mystr} etc.", end="\n\n")

Okay that just proves it! :smiley:

Gotta start reading more of Python Doc…

@tgrtim Thank you for mentioning the end= parameter, I believe I’ve learned that somewhere in the lesson (or not, probably somewhere else). But my desired result is to not write a bunch of “\n” when I need to “dump lots of new lines”.

1 Like