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'
Use
str.partition()to split the string on a newline, and grab the first item from the result:This is the most efficient method if you only need to split a string in a single location. You could use
str.split()too: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:but this has to create separate strings for every newline in the input string so is not nearly as efficient.