How to Create Multi Line String Objects

How to Create Multi Line String Objects in Python ?

A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

In this article we are going to discuss how to create multi line string objects in python.

Create and Convert Multi Line String Objects in Python

Creating multi line string objects:

Converting multi line string objects to single line objects:

Method #1:Using triple quotes

We can assign the multi-line string to a string variable by enclosing it in triple quotes, i.e. either <> or It will be saved in the same multi-line format as before.

Below is the implementation:

# creating multi line string
multistring = '''Hello this is
               BTechGeeks python
               new learning platform'''
# printing the string
print(multistring)

Output:

Hello this is
               BTechGeeks python
               new learning platform

Creating single line string from multi line string

Method #1:Using brackets

If we want to create a string object from multiple long lines but keep them all in a single line, we should use brackets.

Below is the implementation:

# creating single line string from multi line string
singlestring = ("Hello this is "
                "BTechGeeks python "
                "new learning platform")
# printing the string
print(singlestring)

Output:

Hello this is BTechGeeks python new learning platform

Method #2:Using Escape( \ ) symbol

We can also use the escape character to create a single line string object from a long string of multiple lines.

Below is the implementation:

# creating single line string from multi line string
singlestring = "Hello this is "\
    "BTechGeeks python "\
    "new learning platform"
# printing the string
print(singlestring)

Output:

Hello this is BTechGeeks python new learning platform

Method #3:Using join()

We can also make a single line string object by joining several lines together.

Below is the implementation:

# creating single line string from multi line string
singlestring = ''.join(
    ("Hello this is "
     "BTechGeeks python "
     "new learning platform"))
# printing the string
print(singlestring)

Output:

Hello this is BTechGeeks python new learning platform

Related Programs: