Laharl Laharl - 1 year ago 102
Python Question

Python: How do you split a string if the line starts with "ggggg"?

It seems so simple to me, but for some reason I can't get python to split properly on the following.

f = open('text', 'r')
x =
result = x.split('^ggggg', 1)[0]

With file "text" having the following:


I would think "result" would contain everything before the ggggg line, but it just contains the entire text. How do I get python to split where the front of the line starts with "ggggg"?

Answer Source

str.split() does not take a regex.

You could, however, use the string '\nggggg', which will match on a \n, if it's not at the top of a file.

Another possibility is to use the regex functions, documented here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download