How do I read the first line of a string?

PythonString

Python Problem Overview


my_string = """This is my first line,
this is my second line, and...

...this is my fourth line!"""

How can I store the first line of that (This is my first line,) into a separate string? I attempted to use .readline() from another similar question, however I get this error:

AttributeError: 'str' object has no attribute 'readline'

Python Solutions


Solution 1 - Python

Use str.partition() to split the string on a newline, and grab the first item from the result:

my_string.partition('\n')[0]

This is the most efficient method if you only need to split a string in a single location. You could use str.split() too:

my_string.split('\n', 1)[0]

You do then need to tell the method to only split once, on the first newline, as we discard the rest.

Or you could use the .splitlines() method:

my_string.splitlines()[0]

but this has to create separate strings for every newline in the input string so is not nearly as efficient.

Solution 2 - Python

readline is used i conjuction with a stream. you could use StringIO if you insist on using readline:

from StringIO import StringIO

sio = StringIO(my_string)
for sline in sio.readlines():
    print sline

I would do

 for line in my_string.split('\n'):
        print line

or do

import re
for line in re.split('\n', my_string):
    print line

Solution 3 - Python

You can use split():

my_string = """This is my first line,
this is my second line, and...

...this is my fourth line!"""

lines = my_string.split('\n')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1447941View Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonjassinmView Answer on Stackoverflow
Solution 3 - PythonSufian LatifView Answer on Stackoverflow