Mike
Mike

Reputation: 4435

Spliting and Deleteing Values in a Field, Python

I'm trying to fix the values in a field in an access table. The values look like this

G45-f1
C43-m1
C6-h1
M90_N9-h1
K9_Y7-h2

I want to slice away everything before the dash "-" and delete the rest, to look like this:

G45
C43
C6
M90_N9
K9_Y7

I know I can split the values at the dash x.split("-"), but I'm not sure how to delete the remainder. Any suggestions would be welcome.

Upvotes: 0

Views: 58

Answers (3)

Jon Clements
Jon Clements

Reputation: 142226

You can use str.split, but you can also use str.partition which only splits to the first occurence and is always guaranteed to return a 3-tuple... (head, delimiter, tail):

>>> print 'M90_N9-h1'.partition('-')[0]
M90_N9

This has the advantage that should you want tail, then even if the delimiter is not present it will be an empty string, rather than an IndexError exception via str.split.

Upvotes: 1

mingxiao
mingxiao

Reputation: 1812

You could create a new list

newlist = [x.split('-')[0] for x in oldlist]

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124768

str.split() always returns a list with at least one element, just select the first element of the result to ignore the rest:

x.split('-')[0]

You may want to limit the split count, since you are discarding everything but the first part anyway:

x.split('-', 1)[0]

Upvotes: 2

Related Questions