views:

245

answers:

6

In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.

s = 'these-three_words'  
seperators = ('-','_')  
for sep in seperators:  
    s = sep.join([i.capitalize() for i in s.split(sep)])  
    print s  
print s  

stdout:  
These-Three_words  
These-three_Words  
These-three_Words
+6  A: 

capitalize turns the first character uppercase and the rest of the string lowercase.

In the first iteration, it looks like this:

>>> [i.capitalize() for i in s.split('-')]
['These', 'Three_words']

In the second iteration, the strings are the separated into:

>>> [i for i in s.split('_')]
['These-Three', 'words']

So running capitalize on both will then turn the T in Three lowercase.

Paolo Bergantino
+2  A: 

str.capitalize capitalizes the first character and lowercases the remaining characters.

John Kugelman
+5  A: 

You could use title():

>>> s = 'these-three_words'
>>> print s.title()
These-Three_Words
Adam Bernier
+2  A: 

Capitalize() will return a copy of the string with only its first character capitalized. You could use this:

def cap(s):
    return s[0].upper() + s[1:]
Javier Badia
A: 

Answered by John Kugelman and Paolo Bergantino. Thank you both!

You should mark one as the best answer, to show it helped you.
Matthew Flaschen
A: 

Also answered by others, thank you as well!

Stack Overflow is not a forum. Answers do not remain ordered, so do not use them as responses to other answers. Instead, edit the question or add comments -- or in this case, **accept** (click the green check mark) the best answer.
ephemient