Reputation: 11070
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?
Upvotes: 0
Views: 124
Reputation: 304147
>>> 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'
Upvotes: 0
Reputation: 48720
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.
Upvotes: 2
Reputation: 1121644
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'
Upvotes: 5