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?
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?
>>> 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
.
you can try to split with "\n" char like that
>>> a = """this is line1
... this is line2
... this is line3"""
>>> a
'this is line1\nthis is line2\nthis is line3'
>>> a.split("\n")[1]
'this is line2'
You will have n-1 new line character between n lines. Suppose you have 3 lines so you have 2 new line characters.
multiple_lines ="""this is line 1
... this is line 2
... this is line 3
... this is line 4"""
ans=multiple_lines.split(ā\nā)[m-1]
suppose you want to take the mth string from that multiple strings. m-1 because indexing starts from 0, so you if you want to access the 3rd element you will have to do ans[2]