3

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?

  • 1
    Possible duplicate of [How do I split a multi-line string into multiple lines?](https://stackoverflow.com/questions/172439/how-do-i-split-a-multi-line-string-into-multiple-lines) – Georgy Apr 21 '18 at 13:03

3 Answers3

1
>>> 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.

timgeb
  • 76,762
  • 20
  • 123
  • 145
0

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'
FlorentY
  • 11
  • 4
0

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]

Raman Mishra
  • 2,635
  • 2
  • 15
  • 32