Laharl Laharl - 2 months ago 5
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 = f.read()
f.close()
result = x.split('^ggggg', 1)[0]


With file "text" having the following:

aaaaa1234
bbbbb1234
ccccc1234
ggggg1234
hhhhh1234


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

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.