Skip to content
HackoryWEB SECURITY ACADEMYProgramming

Unit 05 · Textos y sus métodos · Lesson 03

Quitar espacios con strip()

strip() saca los espacios del principio y del final.

Lesson content is in Spanish.

Python in your browser

The first time, Python downloads about 5 MB (only once; then it stays saved). If you can, use Wi-Fi.

Python is already saved in this browser: it will not download again.

Python downloads when you start reading.
  1. 01Understand
  2. 02Try
  3. 03Explain

The situation

Cuando alguien copia y pega un texto en un formulario, suelen quedar espacios al principio o al final. No se ven, pero hacen que el largo y las comparaciones fallen.

Understand each piece

  • strip()

    Devuelve el texto sin los espacios de los bordes. Los del medio se quedan: " cable usb ".strip() da cable usb.

  • Corchetes para ver

    Los espacios no se ven en la salida. Si mostrás el texto entre corchetes, f"[{texto}]", ves dónde empieza y dónde termina.

Example

mensaje = "   teclado   "
print(f"[{mensaje}]")
print(f"[{mensaje.strip()}]")

La primera línea muestra los espacios dentro de los corchetes. La segunda muestra [teclado]: strip() sacó los espacios de los dos bordes.

Before moving on: what will happen?

¿Qué va a mostrar este programa?
texto = "  cable usb  "
print(f"[{texto.strip()}]")

Your mission

Limpiá el texto

La prueba crea la variable mensaje. Guardá el mensaje sin espacios en los bordes en una variable limpio y mostrá dos líneas: el texto limpio entre corchetes y su largo. Con mensaje = " ana ", la salida es: [ana] Caracteres: 3

  1. Escribí limpio = mensaje.strip().
  2. Mostrá print(f"[{limpio}]").
  3. Mostrá el largo con f"Caracteres: {len(limpio)}".

If you get stuck

One hint at a time: the first points the way and the last almost solves it.

The key idea

strip() saca los espacios de los bordes y deja los del medio.

Solve with help

If you have already tried, you can see a reference solution. The lesson is marked as solved with help and adds no XP.