DEV Community

Cristian Fernando
Cristian Fernando

Posted on • Edited on

2 1 1

Ibuprofeno.py💊| #12: Explica este código Python

Explica este código Python

Dificultad: Intermedio

def my_fn(precio):
  if(len(precio) == 1):
    return precio.zfill(2)
  if(len(precio) == 2):
    return precio.zfill(3)

print(my_fn("5"))
print(my_fn("50"))
Enter fullscreen mode Exit fullscreen mode
  • A. 5, 50
  • B. 005, 00050
  • C. 05, 050
  • D. 50, 50

Respuesta en el primer comentario.

Top comments (4)

Collapse
 
duxtech profile image
Cristian Fernando • Edited

Respuesta:

  • C. 05, 050

El método zfill de Python es útil para completar con ceros una cadena dada. En el ejemplo verificamos la longitud del precio mandado como argumento, si su longitud es de 1 entonces completamos con ceros hasta que la longitud final sea de 2; así mismo si la longitud del precio es 2 entonces completamos con ceros hasta que la longitud final sea de 3. Eso es todo. ¿Muy fácil no?

Collapse
 
sc0v0ne profile image
sc0v0ne

Very good Paracetamol.py

Collapse
 
duxtech profile image
Cristian Fernando

Thanks! 👌

Collapse
 
sc0v0ne profile image
sc0v0ne

Other examples:

Example 1:

>>> def add_zeros(input: str, amt_zeros: int):
...     return f'{input}'.zfill(amt_zeros)
... 
>>> print(add_zeros("5", 2))
05
>>> print(add_zeros("5", 3))
005
>>> print(add_zeros("50", 3))
050

Enter fullscreen mode Exit fullscreen mode

Example 2:

>>> def add_zeros(input: str):
...     amt_zeros = 2 if len(input) == 1 else 3
...     return f'{input}'.zfill(amt_zeros)
... 
>>> print(add_zeros("5"))
05
>>> print(add_zeros("50"))
050


Enter fullscreen mode Exit fullscreen mode

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay