Objective of str()

Asked

Viewed 69 times

2

I’d like to know what role the function plays str() on line 33(code does not work without this function, gives this error: Typeerror: Unsupported format string passed to list.format)

jogadores = dict()
pontos = list()
while True:
    jogadores['Nome'] = str(input('Nome do jogador: '))
    quant_parti = int(input(f'Quantas partidas {jogadores["Nome"]} jogou? '))
    for c in range(0, quant_parti):
        pontos.append(int(input(f'  => Na {c}° partida, quantos gols {jogadores["Nome"]} fez? ')))
    jogadores['Gols'] = pontos[:]
    jogadores['Total'] = sum(pontos)
    pontos.clear()
    time.append(jogadores.copy())
    jogadores.clear()
    while True:
        opcao = str(input('Deseja continuar? [S / N] ')).upper()
        if opcao in 'SN':
            break
        else:
            print(f'\033[1;31m[ ERROR ]\033[m Tente somente S ou N.')
    if opcao == 'S':
        print('-=-=-='*10)
    if opcao == 'N':
        print('-=-=-='*10)
        break
print('Cód', end=' ')
for k in time[0].keys():
    print(f'{k:>12}', end='')
print()
print('-=-=-='*10)
for i, v in enumerate(time):
    print(f'{i}', end=' ')
    for value in v.values():
        print(f'{str(value):>12}', end=' ')
    print()
print('<<< FIM >>>')```
  • The answer below explained what the str, but to understand because f'{value:>12}' does not work in all cases (as happened in your code, when value is a list), see this question. And for the record, another alternative is to use f'{value!s:>12}', for value!s is equivalent to calling str(value).

1 answer

4


The function str object to transform the received parameter into a string.

If the function receives the number 1 as parameter, you will return the string '1', but she doesn’t just work with numbers.


Take this example:

numero = 10

print(type(numero)) #Aqui será um número (int)

print(type(str(numero))) #Utilizando a função str, torna-se uma string (str)

boolean = True

print(type(boolean)) #Aqui será um boolean (bool)

print(type(str(boolean))) #Utilizando a função str, torna-se uma string (str)

The function str used as above, transformed both the integer and a boolean value into string.

See online: https://repl.it/repls/BreakableUntriedDeclaration


In your example, an error occurs because you are using a string formatting in print:

print(f'{str(value):>12}', end=' ')

Therefore the use of the function str, if you want to do a test, remove the function str and also the formatting, you will see that will no longer generate the cited error, but also of course, the string will no longer be formatted:

print(f'{value}', end=' ')

Documentation: https://docs.python.org/3/library/functions.html#func-str

  • When I saw the question I was intrigued to understand why f'{value:>12}' doesn’t work when value is a list (since with numbers, for example, it works - I thought the value was always transformed into a string before applying the formatting, but with lists gives error and only works if explicitly use str). This ended up generating this question - which is a great add-on, because you just say that the error occurs because of the format of strings, but it’s not quite that (or it’s not only ) - anyway, the link has more details :-)

Browser other questions tagged

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