user1802244
user1802244

Reputation: 51

Python 2.7, add a dash before the last two digits of a string

Using Python 2.7, I want to add a dash before the last two digits of a string, only if string is all numeric.

For example:

1234567 becomes 12345-78

12345TT no change

12345PP678 no change

ABCDEFGH no change

Upvotes: 3

Views: 279

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You don't need a regex to see if a string is all digits, you could use str.isdigit, if it is all digit, slice and add a "-",if not leave as is:

s = "1234578"

s ="{}-{}".format(s[:-2],s[-2:]) if s.isdigit() else s
print(s)
12345-78

It is also more efficient than using a regex.

In [16]: s = "1234578" * 1000

In [17]: r= re.compile(r'^(\d*)(\d{2})$')

In [18]: timeit r.sub(r'\1-\2',s)
1000 loops, best of 3: 459 µs per loop

In [19]: timeit "{}-{}".format(s[:-2],s[-2:]) if s.isdigit() else s
10000 loops, best of 3: 20.7 µs per loop

Upvotes: 5

Avinash Raj
Avinash Raj

Reputation: 174696

I think 1234567 to become 12345-67

re.sub(r'^(\d*)(\d{2})$', r'\1-\2', s)

Upvotes: 1

Related Questions