21. text strings

In addition to numbers, Python can manipulate text or character strings. Text strings can be enclosed in double quotes "" or in single quotes ''.

If we need to use a single quote or a double quote within a text string, we can use the escape character '\':

>>> 'Hola, mundo'  # Comillas simples
    'Hola, mundo'
>>> "doesn't"     # Comillas dobles
    "doesn't"
>>> 'doesn\'t'    # Carácter escape
    "doesn't"

The most commonly used escape symbols are:

\\ -> \
\n -> Nueva línea
\r -> Comienzo de línea
\t -> Tabulación
\b -> Un carácter hacia atrás (backspace)

The text strings can contain Unicode characters, that is, they can contain the letters of the Latin alphabet 'ñ', letters of different alphabets such as the Greek 'Ω ', the Cyrillic 'Я' or even symbols '☀' and emojis '😀'.

Multiline text strings

If you want to write many lines of text, you can include the new line character '\n' in the string or use multiline strings that are enclosed in three single or double quotes:

print("""Este es un ejemplo de una cadena de texto
que ocupa varias líneas.

Al imprimir este texto sale tal y como se ha escrito.""")

Exit:

Este es un ejemplo de una cadena de texto
que ocupa varias líneas.

Al imprimir este texto sale tal y como se ha escrito.

These multi-line texts can be used inside functions to add a help text that explains their operation:

def factorial(n):
   """Devuelve el factorial del número n (n!).
   El factorial es el resultado de multiplicar todos los valores
   enteros desde el número 1 hasta n."""

   mult = 1
   for i in range(2, n+1):
      mult = mult * i
   return mult


help(factorial)

Exit:

Help on function factorial in module __main__:

factorial(n)
    Devuelve el factorial del número n (n!).
    El factorial es el resultado de multiplicar todos los valores
    enteros desde el número 1 hasta n.

The help() function returns the text string of the function to inform us of its operation. All of Python's built-ins have this informational string so you can ask for help on how they work.

union of text strings

To join two text strings we can use the plus symbol:

>>> 'Hola, ' + 'mundo'
    'Hola, mundo'
>>> a = 'Hola, '
>>> b = 'mundo'
>>> a + b
    'Hola, mundo'

Two or more string literals are joined together if they are followed one before the other:

>>> 'Hola ' 'Inés ' '¿Qué tal estás?'
    'Hola Inés ¿Qué tal estás?'

String multiplication

The multiplication symbol can be used to obtain a text several times:

>>> 'Ja ' * 5
    'Ja Ja Ja Ja Ja'
>>> 'Hola, mund' + 'o' * 10
    'Hola, mundoooooooooo'

Exercises

  1. Create a text string with special characters such as accents, Greek letters, symbols, emojis, etc. You can copy and paste from various Internet pages:

  2. Creates a multi-line text string with a double box around a made-up phrase.

    Use these symbols to make the box:

    ╔ ═ ╗
    ║   ║
    ╚ ═ ╝
    
  3. Create a function that prints a 2-row by 2-column table containing 4 made-up numbers.

    The function must have a multi-line text string explaining its purpose.

    Use these symbols to frame the table:

    ╔ ═ ╦ ═ ╗
    ║   ║   ║
    ╠ ═ ╬ ═ ╣
    ║   ║   ║
    ╚ ═ ╩ ═ ╝
    
  4. Write a program that enters a text string on the keyboard and types the number of characters that string has.

    Hint: The len('text') function returns the length, ie the number of characters, of a text string.

  5. Write a function that automatically creates a box around any string we pass to it as an argument.

    Call the function multiple times with different text strings.

    Example:

    recuadro('Hola, mundo')
    

    Exit:

    ╔═════════════╗
    ║ Hola, mundo ║
    ╚═════════════╝
    
    Tracks:
    • It uses character multiplication to print the '═' character multiple times.
    • Use the len(text) function to find out the length of the text string we want to print.