iantheninja
iantheninja

Reputation: 96

converting a list to string and printing it out python

I am trying to convert the first letter of each word of a string to uppercase in python. But i keep getting a generator object at 0x10315b8> no post before this seems to answer my question.

def capitalize(str):
  newstr = str.split(' ')
  newlist = []
  for word in newstr:
    if word[0][0] == word[0][0].upper():
      newlist.append(word[0][0].upper())
      newlist.append(word[0][1:])
      newlist.append(" ")
  convert_first = (str(w) for w in newlist)
  print(convert_first)
capitalize(input("enter some string"))#calling the function

Upvotes: 1

Views: 67

Answers (2)

Gildor
Gildor

Reputation: 2574

There are a few issues with your code:

  1. The error message you got is for trying to print convert_first, which is a generator, not a string.

  2. newstr is a list of words, so word is a string and word[0] is already the first character. Meaningless for word[0][0] or word[0][1:].

  3. if word[0][0] == word[0][0].upper(): just filters all the words whose first character is not uppercase...

So simply some code will do what you described:

def capitalize(str):
  newstr = str.split(' ')
  newlist = []
  for word in newstr:
    newlist.append(word[0].upper())
    newlist.append(word[1:])
    newlist.append(" ")
  convert_first = ''.join(w for w in newlist)
  print(convert_first)
capitalize(input("enter some string"))

Or those who favors short code and generator expressions:

def capitalize(str):
  print(' '.join(word[0].upper() + word[1:] for word in str.split(' ')))
capitalize(input("enter some string"))

This also removes the tailing space of the generated string, which may (not) be what you intended.

Upvotes: 0

hansmosh
hansmosh

Reputation: 511

Your problem lies in how you are trying to make a string out of a list of strings. The opposite of "splitting" a string into a list is "joining" a list into a string.

def capitalize(str):
    newstr = str.split(' ')
    newlist = []
    for word in newstr:
        newlist.append(word[0].upper() + word[1:])
    convert_first = ' '.join(newlist)
    print(convert_first)
capitalize(input("enter some string"))#calling the function

Note: I made an attempt to have my code be as close as possible to that in the question.

Also, why is there an if statement in your code? With that in place you're really just capitalizing all the words that are already capitalized and discarding the rest since they never make it into newlist.

Upvotes: 1

Related Questions