How to Create an Empty String in Python
Python strings are sequences of Unicode characters. A character is simply a symbol. To create a string, use the characters inside a single quote(”) or double-quotes(“”).
Python empty string
To create an empty string in Python, initialize a string containing no characters. Means assign “” to a variable to initialize an empty string.
empty_string = ""
See the following example.
empty_string = "" print(empty_string)
You can see that the second line of the output is empty, which means it’s an empty string.
If you put the spaces inside the double quotes, then it will not count as an empty string. So when you want to create an empty string, always use “” and not ” “.
Check the length of the empty string.
If you check the length of the empty string, use the len() function.
empty_string = "" print(len(empty_string))
You can see that the length of the empty string in Python is 0. The 0 is also a boolean value.
Python empty string is “falsy“, which means they are considered False in a Boolean context.
How to check if String is empty in Python
To check if the string is empty or not, use a not operator.
empty_string = "" print("Check if the string is empty : ", end="") if(not empty_string): print("The string is empty") else: print("No it is not empty")
Check if the string is empty : The string is empty
The string is empty, and one thing to note that we did not even put the space in the string. That is why it returns as empty.
One thing to clarify that the strings are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.
Difference between Python none and empty
The “” indicates a “default” value.
If you want to initialize empty strings and like it as a default value, use the “”.
If you want to check if the variable was set at all, use None.
There is another way to create an empty string.
And it returns an empty string. The str() itself sets a default parameter value of ””.
That is it for this tutorial.