Search code examples
pythonline

How do I read a specific line from a string in Python?


How can I read a specific line from a string in Python? For example, let's say I want line 2 of the following string:

string = """The quick brown fox 
jumps over the
lazy dog."""
line = getLineFromString(string, 2)
print(line)  # jumps over the

There are several questions about reading specific lines from a file, but how would I read specific lines from a string?


Solution

  • There are no primitives in python, so your string is an object. Which has methods, including splitlines().

    my_string = """The quick brown fox 
    jumps over the
    lazy dog."""
    
    line = my_string.splitlines()[1]   # 0 based index, so 1 is the second line
    
    print(line)  # 'jumps over the'