파이썬 방식으로 문자열이 비어 있는지 확인하는 방법

Jinku Hu 2021년7월18일
파이썬 방식으로 문자열이 비어 있는지 확인하는 방법

파이썬에서 문자열이 빈 문자열인지 확인하는 다른 방법이 있습니다. 처럼

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

A 가 아닌 마지막 방법은 PEP8의 Programming Recommendations에서 권장하는 Pythonic 방식입니다. 기본적으로 빈 시퀀스와 컬렉션은 ‘부울’컨텍스트에서 ‘거짓’으로 평가됩니다.

not A가 아닌 것은 Pythonic 일뿐 아니라 가장 효율적이기 때문에 권장됩니다.

>>> 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
작가: 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

관련 문장 - Python String