Проверьте, пуста ли строка в Python
В этом посте мы обсудим, как проверить, пуста ли строка в Python.
1. Использование == оператор
Простое решение — использовать == оператор для сравнения заданной строки с пустой строкой.
В качестве альтернативы вы можете использовать != оператор для проверки непустой строки:
2. Использование not оператор
Pythonic способ проверить пустую строку с помощью not оператора следующим образом:
Чтобы проверить непустую строку, вы можете сделать:
3. Использование len() функция
Наконец, вы можете использовать len() функция для проверки пустой строки, которая возвращает длину строки.
Чтобы проверить непустые строки, вы можете сделать:
Это все, что касается определения того, является ли строка пустой в Python.
Средний рейтинг 5 /5. Подсчет голосов: 22
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно
How to check if the string is empty in Python?
Regardless, what’s the most elegant way to check for empty string values? I find hard coding «» every time for checking an empty string not as good.
26 Answers 26
Empty strings are «falsy» (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
OP wants to know if the variable is an empty string, but you would also enter the if not myString: block if myString were None , 0 , False etc. So if you aren’t sure what type myString is, you should use if myString == «»: to determine if it is an empty string as opposed to some other falsy value.
@AndrewClark, for such a case, instead of a chain of if myString == . expressions, we could use if myString in (None, ») or per @Bartek, if myString in (None, ») or not myString.strip()
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True .
PS: In the PEP’s defense, one could argue that saying «x is false» (lowercase false) already means that, rather than meaning x == False . But IMHO the clarification is still welcome given the target audience.
The most elegant way would probably be to simply check if its true or falsy, e.g.:
However, you may want to strip white space because:
>>> bool("") False >>> bool(" ") True >>> bool(" ".strip()) False
You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.
I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache’s StringUtils.isBlank or Guava’s Strings.isNullOrEmpty
This is what I would use to test if a string is either None OR empty OR blank:
def isBlank (myString): return not (myString and myString.strip())
And the exact opposite to test if a string is not None NOR empty NOR blank:
def isNotBlank (myString): return bool(myString and myString.strip())
More concise for those who care about such things: def isBlank(s): return not (s and s.strip()) and def isNotBlank(s): return s and s.strip() .
I once wrote something similar to Bartek’s answer and javascript inspired:
def is_not_blank(s): return bool(s and not s.isspace())
print is_not_blank("") # False print is_not_blank(" ") # False print is_not_blank("ok") # True print is_not_blank(None) # False
The only really solid way of doing this is the following:
All other solutions have possible problems and edge cases where the check can fail.
- len(myString) == 0 can fail if myString is an object of a class that inherits from str and overrides the __len__() method.
- myString == «» and myString.__eq__(«») can fail if myString overrides __eq__() and __ne__() .
- «» == myString also gets fooled if myString overrides __eq__() .
- myString is «» and «» is myString are equivalent. They will both fail if myString is not actually a string but a subclass of string (both will return False ). Also, since they are identity checks, the only reason why they work is because Python uses String Pooling (also called String Internment) which uses the same instance of a string if it is interned (see here: Why does comparing strings using either ‘==’ or ‘is’ sometimes produce a different result?). And «» is interned from the start in CPython The big problem with the identity check is that String Internment is (as far as I could find) that it is not standardised which strings are interned. That means, theoretically «» is not necessary interned and that is implementation dependant. Also, comparing strings using is in general is a pretty evil trap since it will work correctly sometimes, but not at other times, since string pooling follows pretty strange rules.
- Relying on the falsyness of a string may not work if the object overrides __bool__() .
The only way of doing this that really cannot be fooled is the one mentioned in the beginning: «».__eq__(myString) . Since this explicitly calls the __eq__() method of the empty string it cannot be fooled by overriding any methods in myString and solidly works with subclasses of str .
This is not only theoretical work but might actually be relevant in real usage since I have seen frameworks and libraries subclassing str before and using myString is «» might return a wrong output there.
That said, in most cases all of the mentioned solutions will work correctly. This is post is mostly academic work.
Как проверить, что строка пуста в Python
У вас есть различные методы проверки, является ли строка пустой на Python. Например.
>>> A = "" >>> A == "" True >>> A is "" True >>> not A True
Последний метод not A — это питонический способ, рекомендуемый Programming Recommendations в PEP8. По умолчанию пустые последовательности и коллекции оцениваются как False в Boolean контексте.
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
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.