-2

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Stevoisiak
  • 23,794
  • 27
  • 122
  • 225

2 Answers2

2

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' 
MatBailie
  • 83,401
  • 18
  • 103
  • 137
-1

You can split the string on the newlines, then take the Nth element of the resulting array.

string.split('\n')
# => ['The quick brown fox ', 'jumps over the', 'lazy dog.']

Remember that Python arrays are 0-indexed, so the 2nd element is at index 1.

string.split('\n')[1]
# => 'jumps over the'
nullromo
  • 2,165
  • 2
  • 18
  • 39
  • 3
    This will go wrong if the line break is something else, such as on widows. `splitlines()` takes care of all that. – MatBailie Mar 03 '23 at 22:50
  • @MatBailie's answer is better in general. Please use that unless you specifically need to split on a particular character. – nullromo Mar 03 '23 at 22:52