Johnnerz
Johnnerz

Reputation: 1425

Split a line at the first special character Python

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

Answers (3)

Cricketer
Cricketer

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

user1120144
user1120144

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

TerryA
TerryA

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

Related Questions