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.

Examples:

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

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

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

>>> 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
    6

>>> '  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'
    True
>>> 'á' in 'aeiouáéíóú'
    True
>>> 'n' in 'aeiou'
    False

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

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

Exercises

  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.

    Example:

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

    Clue:

      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
    'texto_nuevo'.
    
  2. Modify the above program so that only the first letter and letters that are at a multiple index of 3 are uppercase.

    Example:

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

    Clue:

    def MayusculaMinuscula(texto):
        texto_nuevo = ''
        for i in range(len(texto)):
            if i % 3 ... :
                ...
            else:
                ...
    
  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.

    Clue:

    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.

    Clue:

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