Reputation: 4064
I have string:
n = 'my fancy extension'
with
''.join([ x.capitalize() for x in n.split() ])
I get MyFancyExtension
, but I need myFancyExtension
.
How do I avoid capitalizing the first item in list, or not capitalizing at all if one word only specified?
Upvotes: 3
Views: 8809
Reputation: 11
n = 'my fancy extension'
n = n.title()
n = n.replace(" ", "")
n = n[0].lower() + n[1:]
print(n)
Upvotes: 1
Reputation:
so, there is nothing in python so I could say ''.join([ x.capitalize() for x in l --if x not first elmnt-- ]), part between -- being some index test?
Actually you can use Python's ternary to achieve such an effect:
x if Condition else y
Or, in this case,
x.capitalize() if Condition else x.lower()
For example:
>>> def camel(my_string):
... my_list = my_string.split()
... return ''.join([x.lower() if x is my_list[0] else x.capitalize() for x in my_list])
>>> camel("lovely to be here")
'lovelyToBeHere'
Where 'x' is a string piece, 'condition' is if x is my_list[0]
, and the two options are of course x.lower()
and x.capitalize()
.
Also kind of nice because if you goof up the first part it will lowercase it for you :)
>>> camel("WHat is the problem")
'whatIsTheProblem'
>>>
In most languages it's written as if Condition x else y
order, instead of x if Condition else y
so a lot of Python folk shy away from it, but personally I think Python's ternary is cool.
Upvotes: 2
Reputation: 36574
Not a fan of dense one-liners, but:
>>> words = "my fancy extension"
>>> ''.join([x.capitalize() if i else x for (i, x) in enumerate(words.split())])
'myFancyExtension'
Upvotes: 3
Reputation: 9116
>>> n = 'my fancy extension'
>>> array = n.split()
>>> array[0] + ''.join(map(str.capitalize, array[1:]))
'myFancyExtension'
Upvotes: 3
Reputation: 7562
l = n.split()
if len(l)>1:
print l[0] + ''.join([ x.capitalize() for x in l[1:] ])
else:
print l[0]
or
import re
print re.sub(" ([a-z])", lambda s: s.group(1).upper(), n)
Upvotes: 1
Reputation: 25974
In python 3 you can do:
n = 'my fancy extension'
first,*rest = n.split()
''.join([first] + [x.capitalize() for x in rest])
Out[10]: 'myFancyExtension'
python 2 doesn't have the fancy extended tuple unpacking syntax, so you'd need an extra step (oh no!):
spl = n.split()
first,rest = spl[0],spl[1:]
Upvotes: 3