Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the nth line of a multiline variable in python

Given a multiple line variables

var="""this is line 1
this is line 2
this is line 3
this is line 4"""

How can I assign to a variable a specific line, say line 2?

like image 805
g2504486.nwytg.com Avatar asked Jan 24 '26 21:01

g2504486.nwytg.com


1 Answers

>>> var="""this is line 1
... this is line 2
... this is line 3
... this is line 4"""
>>> 
>>> line3 = var.splitlines()[3 - 1]
>>> line3
'this is line 3'

str.splitlines splits your multiline-string into distinct lines. line n will be at index n - 1.

like image 132
timgeb Avatar answered Jan 26 '26 11:01

timgeb