简体   繁体   中英

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 + ';'

If your string is in variable x :

import re
re.sub('([a-z]|$)', r';\1', x)
>>> s
'v10:2:34:5h101111gV5H2p1'
>>> ''.join(';'+x if x.islower() else x for x in s)+';'
';v10:2:34:5;h101111;gV5H2;p1;'

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;'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM