24. Formatting text strings

A formatted text string literal is a text string that begins with the letter 'F ' or 'f' and containing replacement fields delimited by braces { }. Replacement fields contain Python variables and, optionally, the formatting to give to the variable's contents.

If you want to print a key, you need to duplicate it: {{ or }}.

Example:

>>> nombre = 'Guido'
>>> apellido = 'van Rossum'
>>> f'El creador de Python es {nombre} {apellido}'
    'El creador de Python es Guido van Rossum'

>>> numero = 7
>>> f'James Bond es el agente {numero:03d}'
    'James Bond es el agente 007'

Exercises

  1. Repeat the following exercise with your own name.

    Exercise:

    >>> nombre = 'Anselmo'
    >>> f'{nombre:>20}'    # Justificado a la derecha
        '             Anselmo'
    >>> f'{nombre:<20}'    # Justificado a la izquierda
        'Anselmo             '
    >>> f'{nombre:^20}'    # Centrado
        '      Anselmo       '
    >>> f'{nombre:_^20}'   # Centrado con relleno '_'
        '______Anselmo_______'
    
  2. Repeat the following exercise with the number variable number = 72. On the last line change the number to your year of birth.

    Exercise:

    >>> nmr = 44
    >>> f'{nmr:10d}'    # Formato decimal entero. Longitud 10
        '        44'
    >>> f'{nmr:+10d}'   # Formato decimal entero con signo. Longitud 10
        '       +44'
    >>> f'{nmr:10X}'    # Formato hexadecimal en mayúsculas. Longitud 10
        '        2C'
    >>> f'{nmr:010b}'   # Formato binario con ceros a la izquierda. Longitud 10
        '0000101100'
    >>> f'{nmr:c}'      # Formato de número a Unicode
        ','
    >>> f'{128512:c}'   # Formato de número a Unicode
        '😀'
    >>> f'{2023:c}'     # Formato de número a Unicode
        'ߧ'
    
  3. Repeat the following exercise with the variable e = 2.71828. Remember that in Python decimals are always separated with a period, not a comma.

    Exercise:

    >>> pi = 3.14159
    >>> # Número de punto flotante con 10 espacios en total y 3 decimales
    >>> f'{pi:10.3f}'
        '     3.142'
    >>> f'{pi:010.3f}' # Igual que el primero, con ceros a la izquierda
        '000003.142'
    >>> f'{pi:10.0f}'  # Igual que el primero, con cero decimales
        '         3'
    >>> f'{pi:10.4e}'  # Igual que el primero, en notación científica
        ' 3.142e+00'
    
  4. Write a program that prompts for a character from the keyboard and returns the next 10 Unicode characters.

    Use the ord() function to convert the character to its Unicode number.

    Clue:

    caracter = input('Introduce un caracter: ')
    numero = ord(caracter[0:1])
    for code in range(numero+1, numero+11):
        print(f'Código: ...  caracter: ... ')
    

    Exit:

    Introduce un caracter: ç
    Código: 0x000E8 caracter: è
    Código: 0x000E9 caracter: é
    Código: 0x000EA caracter: ê
    Código: 0x000EB caracter: ë
    Código: 0x000EC caracter: ì
    Código: 0x000ED caracter: í
    Código: 0x000EE caracter: î
    Código: 0x000EF caracter: ï
    Código: 0x000F0 caracter: ð
    Código: 0x000F1 caracter: ñ
    

    Try entering different characters from the keyboard. Try copying from the Internet and pasting symbols, emojis, Greek and Cyrillic letters, etc.

  5. Write a function that returns the value of an RGB color in Hexadecimal. The three parameters of the function will be three decimal numbers R, G and B (Red, Green and Blue) that must be in the range from 0 to 255. If any number is greater than 255 or less than 0, it must be trimmed to the allowed value .

    Hint: Define a function that limits the value of each number and formats it to hexadecimal format. Then you can define a second function that calls the first function three times with the values ​​of the three colors.

    Remember that hexadecimal values ​​must be in capital letters and must have two digits. The way to convert a variable to two-digit hexadecimal is to add the following format to the variable: f'{variable:02X}'.

    Example:

    rgb(128, 196, 4)
    rgb(500, -5, 64)
    

    Exit:

    80C404
    FF0040