23. String methods

The string methods are functions that work on strings, which are used as argument.

As they are associated with text strings, they are called by adding a period and the name after the text string or after the variable that contains the text string. The argument of the function will be the text string that precedes point.

This is a new way of using functions, which will be studied in greater depth in the section dedicated to Classes in Python and object-oriented programming.


>>> 'PaLaBrA'.upper()    # Mayúsculas

>>> 'PaLaBrA'.lower()    # Minúsculas

>>> 'PALAbra'.swapcase() # Cambia mayúsculas por minúsculas y viceversa

>>> cadena = 'En un lugar de la Mancha'
>>> cadena.title()       # Mayúsculas tipo título
    'En Un Lugar De La Mancha'

>>> cadena.find('lugar') # Busca el texto 'lugar' dentro de la cadena

>>> '  Borra espacios iniciales y finales  '.strip()
    'Borra espacios iniciales y finales'

>>> 'Hola nombre'.replace('nombre', 'Miguel')
    'Hola Miguel'

>>> 'Divide la cadena'.split(' ') # Divide por los espacios
    ['Divide', 'la', 'cadena']

There are many more string methods, but for now with the ones listed we will be able to do most of the operations we need.

in statement

The in statement is used to find out if a text is inside another text:

>>> # ¿Se encuentra el texto 'Hola' en 'Hola, mundo'?
>>> 'Hola' in 'Hola, mundo'
>>> 'á' in 'aeiouáéíóú'
>>> 'n' in 'aeiou'

The statement is case sensitive, so sometimes it can be interesting to use the .lower() method to transform all sentences to lower case and match strings:

>>> # Falso porque no coinciden las letras 'h' y 'H'
>>> 'hola' in 'Hola, mundo'

>>> # Verdadero porque convertimos el texto a minúsculas
>>> 'hola' in 'Hola, mundo'.lower()


  1. Write a function that accepts a string as an argument and returns the string in alternating uppercase and lowercase. The first letter must be uppercase, the second lowercase, the third uppercase, the fourth lowercase, and so on until the end of the text.


    >>> MayusculaMinuscula('Este es un texto de ejemplo')
        'EsTe eS Un tExTo dE EjEmPlO'


      def MayusculaMinuscula(texto):
          texto_nuevo = ''
          mayuscula = True
          for letra in texto:
              if ...
    La variable 'mayuscula' debe cambiar de valor de True a False y
    viceversa cada vez que se añada una nueva letra a la variable
  2. Modify the above program so that only the first letter and letters that are at a multiple index of 3 are uppercase.


    >>> MayusculaMinuscula('Este es un texto de ejemplo')
        'EstE eS uN tExtO dE eJemPlo'


    def MayusculaMinuscula(texto):
        texto_nuevo = ''
        for i in range(len(texto)):
            if i % 3 ... :
  3. Write a program that asks the user for a sentence that describes Lionel Messi without writing any taboo words in that sentence.

    Taboo words are Argentina, Barcelona, ​​soccer.

    The program must detect if any tabu words have been typed regardless of case.


    print('Describe a Lionel Messi sin escribir ninguna palabra tabú.')
    print('Las palabras tabú son: Argentina, Barcelona, futbol, PSG')
    descripcion = input('Descripción: ')
    descripcion = ....                    # Transforma en minúsculas
    if descripcion.find(...) >= 0:
        print('Error, he encontrado la palabra tabú ... en la descripción')
    elif ...
  4. Write a function that accepts a string as an argument and returns the string with all vowels replaced by another vowel we set in the second argument. Call the function with several example sentences to test how it works.

    By default the replacement vowel will be 'e'.

    To facilitate the program we will transform the text to lower case.


    def reemplaza_vocales(texto, vocal='e'):
        # Transforma en minúsculas
        texto = texto...
        # Reemplaza todas las vocales
        texto = texto.replace('a', vocal)
        return texto