Python - Deleting the first 2 lines of a string

2019-04-19 12:33发布

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:

version 1.00
6992
[-4.32063, -9.1198, -106.59][0.00064, 0.99993, -0.01210][etc...]

I want to remove the first two lines of this Roblox mesh file for a script I am using. How can I do that?

5条回答
Luminary・发光体
2楼-- · 2019-04-19 12:43

I'd rather not split strings in case the string is large, and to maintain newline types afterwards.

Delete the first n lines:

def find_nth(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start
assert s[find_nth(s, '\n', 2) + 1:] == 'c\nd\n'

See also: Find the nth occurrence of substring in a string

Or to delete just one:

s = 'a\nb\nc\nd\n'
assert s[s.find('\n') + 1:] == 'b\nc\nd\n'

Tested on Python 3.6.6.

查看更多
做自己的国王
3楼-- · 2019-04-19 12:48
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.

查看更多
趁早两清
4楼-- · 2019-04-19 12:57

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]
查看更多
Juvenile、少年°
5楼-- · 2019-04-19 13:00

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.

查看更多
【Aperson】
6楼-- · 2019-04-19 13:02

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

查看更多
登录 后发表回答