How to Convert Multiline String to List in Python

Hello friends, in this tutorial, we will learn how to convert a multiline string to a list in Python. Multiline strings are represented using newline characters or using triple quotes.

  • Representing multiline string using newline characters:
          my_string='This is Codespeedy.\nyou can learn to program here.'
  • Representing multiline string using triple quotes:
          my_string=''' This is Codespeedy.
          you can learn to program here.'''

So, now we will see how to convert these types of strings into a list using Python.

Convert Multiline String to List in Python

We can convert a multiline string into a list using any of the two methods.

  1. splitlines()
  2. split()

1. splitlines() method:

  • Syntax:
     string_name.splitlines([keepends])
  • Parameter:

Parameter ‘keepends‘ is optional. The default value is False. If we want to keep the end characters i.e newline character ‘\n’, we have to pass the parameter as True.

  • Return value:

This method returns a list of strings breaking at the newline character.

  • Code:
my_string='This is Codespeedy.\nyou can learn to program here.'
my_list=my_string.splitlines()
print(my_list)

Output:

['This is Codespeedy.', 'you can learn to program here.']

In the above code, ‘splitlines()‘ takes no parameter.

my_string='This is Codespeedy.\nyou can learn to program here.'
my_list=my_string.splitlines(True)
print(my_list)

Output:

['This is Codespeedy.\n', 'you can learn to program here.']

In the above code, ‘splitlines()‘ takes True as the parameter.

Now, we will see if the multiline string is represented using triple quotes, then the code works or not.

my_string=''' This is Codespeedy.
you can learn to program here.'''
my_list=my_string.splitlines()
print(my_list)

Output:

[' This is Codespeedy.', 'you can learn to program here.']

Yes, it is working fine.

2. split() method:

  • Syntax:
    string_name.split()
  • Parameter:

We have to pass the character with respect to which we want to split i.e the newline character ‘\n’ as the parameter.

  • Return Value:

This method returns a list of strings breaking at the newline character.

  • Code:
my_string=''' This is Codespeedy.
you can learn to program here.'''
my_list=my_string.split('\n')
print(my_list)

Output:

[' This is Codespeedy.', 'you can learn to program here.']
my_string=' This is Codespeedy.\nyou can learn to program here.'
my_list=my_string.split('\n')
print(my_list)

Output:

[' This is Codespeedy.', 'you can learn to program here.']

So, we have seen how to convert multiline strings to list using Python.

Applications:

Mainly, we need this conversion when we want to traverse or access each line from a text file.

You may also read:

Leave a Reply

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