How does the following output come?
>>> a
'hello'
>>> a = list(a)
>>> a
['h', 'e', 'l', 'l', 'o']
>>> a = str(a)
>>> a
"['h', 'e', 'l', 'l', 'o']"
>>> a.title()
"['H', 'E', 'L', 'L', 'O']"
>>> a[0]
'['
>>> a[1]
"'"
>>> a[2]
'h'
When title has to capitalize only the first letter of the string, how does every letter get capitalized?
-
You created a list. Then the string conversion of the list. What output did you expect instead?Martijn Pieters– Martijn Pieters2014年05月31日 10:50:56 +00:00Commented May 31, 2014 at 10:50
-
@MartijnPieters: Either there should be no change, or only 'h' should be capitalized. Isn't that how title works?Aswin Murugesh– Aswin Murugesh2014年05月31日 10:52:37 +00:00Commented May 31, 2014 at 10:52
3 Answers 3
str() does not join a list of individual characters back together into a single string. You'd use str.join() for that:
>>> a = list('hello')
>>> ''.join(a)
'hello'
str(listobject) returns a string representation of the list object, not the original string you converted to a list. The string representation is a debug tool; text you can, for the most part, paste back into a Python interpreter and have it recreate the original data.
If you wanted to capitalise just the first characters, use str.title() directly on the original string:
>>> 'hello'.title()
'Hello'
>>> 'hello world'.title()
'Hello World'
Comments
I think you're confused about how title works.
In [5]: s = "hello there"
In [6]: s.title()
Out[6]: 'Hello There'
See how it capitalises the first letter of each word? When you str() the list, it no longer sees hello as a single word. Instead, it sees each letter on its own and decides to capitalise each letter.
Comments
>>> a=list('hello')
>>> str(a)
"['h', 'e', 'l', 'l', 'o']"
>>> len(str(a))
25
So you have a string of 25 characters. All those ',, etc. are part of the string. title sees 5 one-character words, so each one is upper cased. Try ''.join instead
>>> ''.join(a)
'hello'
>>> len(''.join(a))
5
>>> ''.join(a).title()
'Hello'