0

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?

2
  • You created a list. Then the string conversion of the list. What output did you expect instead? Commented 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? Commented May 31, 2014 at 10:52

3 Answers 3

5

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'
Sign up to request clarification or add additional context in comments.

Comments

2

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

0
>>> 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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.