Doubt about the replace() method

Asked

Viewed 59 times

0

The replace() method is a method of the str class, correct?

Follows a code that 'rotates' perfectly where the object is an integer (or at least in my interpretation). Or in the case of interpolation this changes?

Follows:

def moeda(valor, moeda = 'R$'):
    return f'{moeda}{valor:.2f}'.replace('.', ',')


velocidade = float(input('Qual é a velocidade do carro? (KM) '))
if velocidade > 80:
    print('VELOCIDADE PERMITIDA ULTRAPASSADA!')
    print('\033[1;31mMULTADO!\033[m')
    multa = (velocidade - 80) * 6
    multa = moeda(multa)
    print(f'Você foi multado em {multa}')
else:
    pass

PS. The currency() function transforms an integer number into a currency format, replacing integer points with commas.

  • is a fstring, I think ta normal, because the number is formatted inside the string, and then the string is changed by replace. I think looking at the point between the string and replace, this object orientation indicates that replace will act on the output of the freight method

1 answer

1


As you said yourself, replace is a string and value method of the type int or float nay possess him.

What happens in your code is that you pass the value into a new string using string formatting f-string. So you are using the method replace of a str created in the format and not a numeric value. See the example below:

valor = 75.99
string_valor = f"R$ {valor}"

print(type(string_valor), "-", string_valor)  # <class 'str'> - R$ 75.99

string_valor = string_valor.replace(".", ",")
print(string_valor)
  • Perfect Jean. I figured that’s right! F-Strings get string treatment. Thank you!

  • A f-string actually works like a method call - it does almost the same as calling .format, with the appropriate parameters, for the same string. - Even, and this is important, it will only have the final value when its line of code is executed. Normal strings already have the end value when the file is compiled to bytecode.

Browser other questions tagged

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