Cómo comprobar si una cadena está vacía de forma ptónica

Jinku Hu 25 junio 2020 Python Python String
Cómo comprobar si una cadena está vacía de forma ptónica

Tienes diferentes métodos para comprobar si un string es un string vacío en Python. Como

>>> A = ""
>>> A == ""
True
>>> A is ""
True
>>> not A
True

El último método not A es una forma pythonica recomendada por Recomendaciones de Programación en PEP8. Por defecto, las secuencias y colecciones vacías se evalúan como False en un contexto Boolean.

Se recomienda not A no sólo porque es pythonica, sino también porque es la más eficiente.

>>> timeit.timeit('A == ""', setup='A=""',number=10000000)
0.4620500060611903
>>> timeit.timeit('A is ""', setup='A=""',number=10000000)
0.36170379760869764
>>> timeit.timeit('not A', setup='A=""',number=10000000)
0.3231199442780053
¿Disfrutas de nuestros tutoriales? Suscríbete a DelftStack en YouTube para apoyarnos en la creación de más guías en vídeo de alta calidad. Suscríbete
Autor: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Artículo relacionado - Python String