Search code examples
pythonstringline

How would I print multiple lines of text in a single print statement?


The idea would be this:

a = input("insert name: ")
a
print("hi ", a, "!")
print("hello", a, "!")
print("good morning", a, "!")

but I need to know if there's a way to get all that prints in 1 unique thing but wrapping text kinda like this: print("hi ", a, "!" wrap "hello", a, "!" wrap "good morning", a, "!")

Ty in advance


Solution

  • I can think of two ways:

    • print("hi ", a, "!\n", "hello", a, "!\n", "good morning", a, "!") - using the \n newline control character (see this question for more info).
    • A generator for the same sort of thing, but easier since it inserts the \n for you:
    def join(text):
      for i in range(len(text)):
        text[i] = [item if isinstance(item, str) else ''.join(item) for item in text[i]]
      lines = [' '.join(item) for item in text]
      return '\n'.join(lines)
    
    # Usage:
    print(join([[["hi ", a, "!"]], ["hello", [a, "!"]], ["good morning", a, "!"]]))
    
    # Equal to:
    print("hi " + a + "!")  # See how nested items (e.g [a, "!"] in ["hello", [a, "!"]]) represent simple concatenation (the equivalent of `+` in `print()`)
    print("hello", a + "!")  # while sister items (e.g "good morning" and a in ["good morning", a, "!"]) represent joining with space (the equivalent of ',' in `print()`)
    print("good morning", a, "!")
    

    Explanation:

    1. Go through and find where to concatenate, and where to delimit, strings.

      1a. for i in range(len(text)):: loop through the array, storing the current array index

      1b. [item if isinstance(item, str) else ''.join(item) for item in text[i]]: Let's break this down. We take the current item - represented by text[i] (since this is inside the for loop, each item looks something like ["hello", [a, "!"]]) - and loop through it. So, the variable item will have values that look either like "hello" or [a, "!"]. Next, we use isinstance to check if the the item is a string. If so, we just leave it. Otherwise, it's an array, so we concatenate all of the values in it together with no delimiter. So, the full example would be: [[["hi ", "dog", "!"]], ["hello", ["dog", "!"]], ["good morning", "dog", "!"]] becomes [["hi dog!"], ["hello", "dog!"], ["good morning", "dog", "!"]]

    2. lines = [' '.join(item) for item in text]: creates an array with each item in text, a nested array, but joined together using . This results in flattening the nested array into a basic 1D array, with each individual array of items replaced by a version separated by spaces (e.g [['hi', 'my', 'friend'], ['how', 'are', 'you']] becomes ['hi my friend', 'how are you'])

    3. '\n'.join(lines) joins together each string in the flat array, using the \n control character (see link above) as a delimiter (e.g ['hi my friend', 'how are you'] becomes 'hi my friend\nhow are you')