create multiline string in python

How to Create Multiline String in Python

Python is a powerful programming language that allows you to do many useful things with strings and textual data. Often you may need to store a really long string in a variable. One common way to do this is to create multiline string in Python. Multiline string is a string that spans across multiple lines of code but is a single value assigned to a variable, or used in a function or other places. This improves code readability and makes it easy to even modify your data. In this article, we will learn how to create multiline string as well as how to use inline variables in them. This problem is generally faced by beginners in python.


How to Create Multiline String in Python

You can create multiline string using backslash ‘\’ operator. Here is an example of a multiline string.

address = "123, High Street \
          New York, NY"
print(address)

You will get the following output.

123, High Street           New York, NY

Please note, you need to add backslash at the end of line before the ending quotes. If you have more than 2 lines, you need to add backslash at end of each line.

address = "123, High Street \
          New York, NY, \
          ph:454-565-7676"

Please note, the multiline string will be output as a single line string, unless you add a newline character for line break.

Here is an example of adding newline character to even display the output as multiline

address = "123, High Street \n \
          New York, NY"
print(address)

You will get the following output.

123, High Street
          New York, NY

If you want to pass inline variables in your multiline string you can do so using format() function.

>>> s = "This is an {example} \
          with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'

In the above example, we pass two variables vars and example in our multiline string.

You can also pass a dictionary of variables in a string, using format() function.

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)

The key difference is that you have to pass reference to your dictionary by prepending ** to it.

In this article, we have learnt how to create multiline string in Python and also use inline variables in them.

Also read:

How to Put Variable in String in Python
How to Fix ValueError: setting array element with sequence
How to Fix ‘ASCII codec can’t encode’ error in Python
How to Print Curly Braces in String in Python
How to Set Timeout on Function Call in Python

Leave a Reply

Your email address will not be published. Required fields are marked *