Python provides different presentations for the string data type. The string is used to store non or multiple characters in a variable where it can store 0 or 1 characters string or 100 characters string. While defining or setting long strings is easy but reading this string from code is very hard. A single string can be split into multiple lines which will increase the readability of the string.
Use Triple Quotes For Multiline String
The most popular method to create a multiline string in Python is using triple quotes. The string value starts with a triple quote and the string value provided in single or multiple lines where the end of the string is set again using triple quotes. Let’s make an example by using triple quotes for the multiline string.
mystr = """This is a multiline
string """
print(mystr)
mystr = """This
is
a
multiline
string """
print(mystr)
mystr = """This
is
a
string """
print(mystr)
The output will contain multi line string according to the provided structure with new lines and spaces.
Use Brackets For Multiline String
Another way to create multiline string inPython is using brackets where the start of the string will be a starting bracket and end of the string contain ending bracket. The strings will be put line by line where every line will contain a single string in double quote.
mystr = ("This is a multiline
"
"string "
)
print(mystr)
mystr = ("This
"
" is"
" a"
" multiline"
" string"
)
print(mystr)
mystr = ("This
is
a
string ")
print(mystr)
Use Backslash For Multiline String
The backslash is a special sign which is also used in other programming languages in order to create multiline strings. The backslash will put every end of the line as well as the string definition line. Only the last line will not contain a backslash.
mystr = "This is a multiline
"
\
"string "
print(mystr)
mystr = "This
"
\
" is"
\
" a"
\
" multiline"
\
" string"
print(mystr)
mystr = "This
is
a
string "
print(mystr)
Use Join() Method For Multiline String
join()
is a method provided by Python for the string data types. By using a string literal like ” which will provide the join method a multiline string can be created by providing every line as a separate string. Keep in mind that every string will be printed as separate lines as a new line added for every separate string parameter.
mystr =''.join("This
"
, " is" , " a"
, " multiline"
, " string"
)
print(mystr)