Skip to content Skip to sidebar Skip to footer

Python - Deleting The First 2 Lines Of A String

I've searched many threads here on removing the first two lines of a string but I can't seem to get it to work with every solution I've tried. Here is what my string looks like: ve

Solution 1:

I don't know what your end character is, but what about something like

postString = inputString.split("\n",2)[2]

The end character might need to be escaped, but that is what I would start with.

Solution 2:

x="""version 1.00
6992
[-4.32063, -9.1198, -106.59][0.00064, 0.99993, -0.01210][etc...]
abc
asdda"""print"\n".join(x.split("\n")[2:])

You can simply do this.

Solution 3:

Remove the lines with split:

lines = """version 1.00
6992
[-4.32063, -9.1198, -106.59][0.00064, 0.99993, -0.01210][etc...]"""lines = lines.split('\n',2)[-1]

Solution 4:

''.join(x.splitlines(keepends=True)[2:])

splitlines produces a list of strings. If keepends=True is given, line breaks are included in the resulting list l and ''.join(l) can be used to reproduce the original string.


Note that splitlines works well with a number of different line boundaries such as \u2028

>>>x = 'a\u2028b\u2028c\u2028'>>>''.join(x.splitlines(keepends=True)[2:])
'c\u2028'

while split('\n') fails in this case:

>>> x ='a\u2028b\u2028c\u2028'>>> x.split('\n',2)[2]
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
IndexError: list index outofrange

Also note that splitlines and split('\n') behave differently if they are called on an empty string or a string that ends with a newline character. Compare the following examples (copied from the documentation of splitlines):

>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']

>>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']

However, if keepends=True is given, the trailing newline is preserved:

>>> "One line\n".splitlines(keepends=True)
['One line\n']

More examples and a list of what splitlines treats as a line boundary can be found here: https://docs.python.org/3/library/stdtypes.html?highlight=split#str.splitlines

Solution 5:

You could use some rules, like consider those lines only if they start with '[' character lines = [line for line in lines if line.startswith('[')]

Post a Comment for "Python - Deleting The First 2 Lines Of A String"