Reputation: 2229
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2
or stArTDate(%Y/%m)==11/3
and I want to convert it to formatdate(%M)==2
or startdate(%Y/%m)==11/3
i.e. change it to lowercase except the part in between the braces ()
. For the first example, I came up something like this:
>>> import re
>>> fdt = re.compile('(F|f)(O|o)(R|r)(M|m)(A|a)(T|t)(D|d)(A|a)(T|t)(E|e)\(')
>>> ss = "forMatDate(%M)==2"
>>> if fdt.match(ss):
... SS = ss.split('(')
... SS[0] = SS[0].lower()
... ss = "(".join(SS)
...
>>> print ss
formatdate(%M)==2
Whilst it works just fine, I didn't quite like it doing this way. The regular expression is ugly and it makes thing pretty much restricted to a particular string. Is there any better (hence, dynamic) way of doing that? Thanks in advance. Cheers!!
I probably didn't say it very clearly: it's not always formatdate()
, sometimes it's startdate()
or enddate()
along with UserName==JohnDee
and so on.. (it's part of the user-input) but the format is always the same and I wanted something reusable. So, this is the updated version based on Krumelur's
script.
>>> fdt = re.compile('\(%[dmwyMW].*\)')
>>> ss = "formatDate(%M)==4"
>>> st = "UserName==JohnDee"
>>>
>>> def dt_lower(sX):
... if fdt.search(sX):
... p1,p2 = sX.split('(',1)
... sX = "%s(%s" % (p1.lower(), p2)
... else: sX = sX.lower()
... return sX
...
>>> print dt_lower(ss)
formatdate(%M)==4
>>>
>>> print dt_lower(st)
username==johndee
This is exactly what I wanted. Thanks everyone for helping. Cheers!!
Upvotes: 3
Views: 310
Reputation: 32497
Do your strings always look exactly like this? If so, maybe this is enough:
p1,p2 = instr.split('(',1)
lc = '%s(%s' % (p1.lower(), p2)
Upvotes: 5
Reputation: 141770
I don't think you can get much more "Pythonic" than this:
Python 2.7.1 (r271:86832, May 27 2011, 21:41:45)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ss = "forMatDate(%M)==2"
>>> if ss.lower().startswith('formatdate'):
... i,j = ss.split('(', 1)
... ss = '('.join((i.lower(), j))
...
>>> ss
'formatdate(%M)==2'
No need for regular expressions, just built-in string methods
.
Also works in Python 3.2.
Upvotes: 3
Reputation: 1188
Just to add to Krumerlur's answer,u may want to make it
p1,p2 = inst.split( '(' , 1 )
Upvotes: 2
Reputation: 53819
I don't really get why you are using a regular expression? Why don't you just do:
x, y = ss.split('(')
'('.join((x.lower(), y))
Upvotes: 2
Reputation: 31941
You can replace your regex check with
if ss.lower().startswith('formatdate'):
Upvotes: 2