Reputation: 1425
So I have a line of text like this getting read into my program:
00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000
And I want to split that in two at the first special character. Most of the time the line is split by the '@' symbol, but in some cases a different character comes up. ('~', '+', '#p', '#m', '%p', '=').
So far I have it working for the '@' character:
def split_pointer_part(self, line):
self.before_at, self.after_at = line.partition('@')[::2]
return self.before_at, self.after_at
How do I change this to work for the first one that shows up out of the list of special characters?
Upvotes: 0
Views: 1356
Reputation: 2431
One approach is to check if any of the special character comes up. Lets store the first special character that came up in the variable specialChar
. You can now call line.partition(specialChar)
.
Upvotes: 0
Reputation:
Take a look at re.split. It works like the regular split but accepts a regular expression.
Example:
import re
string = "00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000"
print(re.split(r'\@|\~|\+|\#p|\#,|\%p|\=', string))
Upvotes: 0
Reputation: 60014
You can use a regular expression:
>>> import re
>>> line = "00001740 n 3 eintiteas aonán beith 003 @ 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000"
>>> re.split(r'(?:#p|#m|%p|[@~+=])', line, 1)
['00001740 n 3 eintiteas aon\xc3\xa1n beith 003 ', ' 00001930 n 0000 ~ 00002137 n 0000 ~ 04424418 n 0000']
Upvotes: 2