Reputation: 38
I've a string having CUSTOMER_SEGMENT_PRIV
and want to get an output of CUSTOMER_SEGMENT equal to PRIV
>>> re.sub('_{1}',' ot lauqe ','CUSTOMER_SEGMENT_PRIV'[::-1])[::-1]
'CUSTOMER equal to SEGMENT equal to PRIV'
>>> re.sub('((?:_[^_\r\n]*){1})$',' ot lauqe ','CUSTOMER_SEGMENT_PRIV'[::-1])[::-1]
'CUSTOMER equal to SEGMENT equal to PRIV'
What I want:
'CUSTOMER_SEGMENT equal to PRIV'
Upvotes: 1
Views: 52
Reputation:
A shorter way using a good regex :
>>> import re
>>> re.sub( r'_([^_\r\n]*)$', ' equal to \\1', 'CUSTOMER_SEGMENT_PRIV' )
'CUSTOMER_SEGMENT equal to PRIV'
Upvotes: 1
Reputation: 32944
No need to use regex, just use str.rsplit
with maxsplit=1
and str.join
:
>>> s = 'CUSTOMER_SEGMENT_PRIV'
>>> x = s.rsplit('_', 1)
>>> x
['CUSTOMER_SEGMENT', 'PRIV']
>>> ' equal to '.join(x)
'CUSTOMER_SEGMENT equal to PRIV'
Upvotes: 1