How to use the title() method in Python?

Asked

Viewed 1,061 times

0

How do I use the title() in Python in a list, tuple, set?

Exemplos que não executam:

lista = ['banana', 'mamão', 'maçã']
print (lista.title())

tupla = ('banana', 'mamão', 'maçã')
print (tupla.title())

seta = {'banana', 'mamão', 'maçã'}
print (seta.title())
  • The words list, tuple and set are built-in (built-in Function) python functions. Do not use these words as variables.

1 answer

5


The function title() is a function that is associated with str of Python, that is, you can only use it if it is in a string. If you have a list of strings and wants each of the list to be capitalized with the function title, you have to scroll through the list and add the function title for each of them, this serves for any interfacing in Python, as list, set, tuple, etc. A simple way to do this without having to create a block for to go through your strings is using the comprehensions of Python, it would look like this.

lista =['laranja', 'mamão', 'maçã']
nova_lista_captalizada = [ i.title() for i in lista]


tupla = ('banana', 'mamão', 'maçã')
nova_tupla = tuple( i.title() for i in tupla)

# O modo de cima é a mesma coisa que a debaixo
nova_lista_captalizada =[]
for i in lista:
     nova_lista_captalizada.append(i.title())

If you still don’t know the comprehensions in Python, no problem, you need to understand here, that function title(), is related to str in Python.

  • I don’t understand and the code doesn’t run.

  • 1

    @Alexfelician title is a method defined in the class str and does not exist in the classes list, set and tuple as you used in the question.

  • Hi Robson - the answer in "new tuple" does not create a tuple - but a "Generator Expression" - a Lazy iterator that Ger the elements if used in a for or with the call next . To create a tuple it is necessary: nova_tupla = tuple( i.title() for i in tupla). But congratulations on the answer and explanations as a whole!

  • jsbueno, well noted, it is true will return Generator. Obliged by the correction.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.