DanielTA
DanielTA

Reputation: 6548

Python, Regular Expression help. Insert with re

I want to know how to convert this string:

v10:2:34:5h101111gV5H2p1

to this:

;v10:2:34:5;h101111;gV5H2;p1;

So in words, I want to know how to insert ';' before all lowercase letters. I can just add the ';' at end with:

str = str + ';'

Upvotes: 0

Views: 941

Answers (3)

Burhan Khalid
Burhan Khalid

Reputation: 174624

>>> s
'v10:2:34:5h101111gV5H2p1'
>>> ''.join(';'+x if x.islower() else x for x in s)+';'
';v10:2:34:5;h101111;gV5H2;p1;'

Upvotes: 3

Mu Mind
Mu Mind

Reputation: 11194

If your string is in variable x:

import re
re.sub('([a-z]|$)', r';\1', x)

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

a non-regex approach:

In [11]: from string import ascii_lowercase

In [12]: strs="v10:2:34:5h101111gV5H2p1"

In [13]: ''.join(';'+x if x in ascii_lowercase else x for x in strs)+';'
Out[13]: ';v10:2:34:5;h101111;gV5H2;p1;'

or:

In [16]: ''.join(';'+x if x.lower()==x and x.isalpha() else x for x in strs)+';'

out[16]: ';v10:2:34:5;h101111;gV5H2;p1;'

Upvotes: 2

Related Questions