Use the str.isspace() method:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

Combine that with a special case for handling the empty string.

Alternatively, you could use str.strip() and check if the result is empty.

Answer from Vladislav on Stack Overflow
🌐
Programiz
programiz.com › python-programming › methods › string › isspace
Python String isspace()
The isspace() method returns True if there are only whitespace characters in the string. If not, it return False.
Discussions

Isspace function in python - Stack Overflow
I suggest reading the documentation in these cases. For isspace, note here that · Return True if there are only whitespace characters in the string and there is at least one character, False otherwise. More on stackoverflow.com
🌐 stackoverflow.com
Python isspace function - Stack Overflow
I'm having difficulty with the isspace function. Any idea why my code is wrong and how to fix it? Here is the problem: Implement the get_num_of_non_WS_characters() function. More on stackoverflow.com
🌐 stackoverflow.com
python - Check if string is None, empty or has spaces only - Stack Overflow
A bool of string that has spaces is True in Python. We cannot call any method, such as isspace() or strip(), on a None object. ... That looks reasonable, though perhaps you could think about ways to exclude None by other means earlier in the code. ... This has a little benefit over your original way that not ... More on stackoverflow.com
🌐 stackoverflow.com
using isspace() to check if it is a single word
That method checks if all characters in a string are whitespace. Something like check: bool = not ' ' in x print(check) should work. More on reddit.com
🌐 r/learnpython
14
1
March 6, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-string-isspace-method
Python String isspace() Method - GeeksforGeeks
January 2, 2025 - Returns False if the string contains one or more non-whitespace characters or is empty. Let's see what happens when the string contains non-whitespace characters: ... The string contains non-whitespace characters ("Python ...
🌐
W3Schools
w3schools.com › python › ref_string_isspace.asp
Python String isspace() Method
Remove List Duplicates Reverse ... Q&A Python Bootcamp Python Training ... The isspace() method returns True if all the characters in a string are whitespaces, otherwise False....
Top answer
1 of 4
1

I don't think the str.isspace, str.isalpha and str.isdigit methods do what you expect them to do. To start with, they all test if all the characters in the string you enter are of the type that is described in their name. Your code seems to be expecting them to be return True if any of the characters match. That is, if there are any spaces, you want to remove them and show the two lengths, before and after.

There's no single string method that will do that test for you in Python. You could use regular expressions (which are more powerful, but much more complicated), or you could write some slightly more elaborate code to do the test. I'd suggest using the any function, and passing it a generator expression that calls the method you want on each character in the string.

if any(c.isspace() for c in user_str):
    ...

This may not be exactly what you want for all of your tests. The desired logic of your code is not entirely obvious, as there are a number of corner cases that your output doesn't specifically address. Is a string that contains both letters and numbers valid? How about one that has spaces in between numbers, but no letters at all? You may need to reorder the conditions of your if/elif/else statements so that they match what you intend.

I'd also note that the variable name you used for user input, new_length, is very misleading. It's not a length, its the string you want to measure the length of! It's a lot easier to make logic errors about variables that have misleading or unclear variable names, so taking time to go back and reconsider names you chose earlier is sometimes a good idea, as it can improve the clarity of your code a lot! Descriptive variable names are good, but it's a tradeoff between clarity and brevity, as long names are tedious to type (and prone to typos). They also can lead to line length issues, which can make it less convenient to see all your code on your editor screen at once.

2 of 4
0

You can use this function to check if the input string contains a number:

def hasNumbers(inputString):
        return any(char.isdigit() for char in inputString)

It returns true if there is a number and false if there is not.

As for the whitespaces you can ommit isspace(). Using replace() alone will do the job, even if there are no whitespaces.

stri='jshsb sjhsvs jwjjs'
stri=stri.replace(' ','')
🌐
Linux Hint
linuxhint.com › python-string-isspace-method
Linux Hint – Linux Hint
October 24, 2022 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
AskPython
askpython.com › python › string › python-string-isspace
Python String isspace() method - AskPython
February 16, 2023 - The .astype() function converts the non-string type data to string type. ... import pandas inp_data = pandas.Series(['Jim', 'Jonny', ' ', '\t', 'Daisy', '\n']) res = inp_data.str.isspace() print(res) ... In this article, we have understood the functioning of the Python string isspace() method.
Find elsewhere
🌐
EyeHunts
tutorial.eyehunts.com › home › python check if string is empty or whitespace | example code
Python check if a string is empty or whitespace | Example code - EyeHunts
July 19, 2021 - # string only space str1 = " " print(str1.isspace()) # string without space str2 = "" print(str2.isspace()) ... Empty strings are “falsy” which means they are considered false in a Boolean context, so you can just use not string.
🌐
PythonHello
pythonhello.com › problems › string › how-to-check-if-string-is-empty
Checking if a string is empty in Python
string = " \t\n" if string.isspace(): print("The string is empty") else: print("The string is not empty")
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › str › isspace.html
isspace — Python Reference (The Right Way) 0.1 documentation
For 8-bit strings, this method is locale-dependent. Returns False if string is empty. >>> ''.isspace() False >>> 'abc123'.isspace() False >>> 'abc'.isspace() False >>> '123'.isspace() False >>> 'Abc'.isspace() False >>> '!@#'.isspace() False >>> ' '.isspace() True >>> 'ABC'.isspace() False
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › string › isspace › python-string-isspace
Python isspace() function | Why do we use Python String isspace()? |
August 26, 2021 - In the above example, all the input strings are entirely made up of white spaces. As a result, the isspace() method returns True. Even if one character is not a whitespace, the isspace() method will return False, as seen below.
🌐
Tutorialspoint
tutorialspoint.com › python › string_isspace.htm
Python String isspace() Method
Are all the characters of the string spaces? False · The horizontal tab space '\t' is a white space character. Let us test this using an example. str = "\t\t\t" result=str.isspace() print("Are all the characters of the string spaces?", result)
🌐
PythonForBeginners.com
pythonforbeginners.com › home › check if a string is empty or whitespace in python
Check if a String is Empty or Whitespace in Python - PythonForBeginners.com
August 8, 2022 - In Python, all the iterable objects like strings, lists, and tuples evaluate to False when they are empty. Therefore, an empty string evaluates to False. To check if a string is empty or whitespace using the not operator, we will use the not operator on the input string.
🌐
EyeHunts
tutorial.eyehunts.com › home › isspace python function | check if a string has space
isspace() Python function | Check if a string has space - EyeHunts
July 16, 2021 - The "isspace Python function" is used to check if there are only whitespace characters in the string. Python String isspace() will return boolean value, if
🌐
Finxter
blog.finxter.com › home › learn python blog › python string isspace()
Python String isspace() – Be on the Right Side of Change
March 23, 2021 - Border case: The empty string is not be considered a whitespace character! >>> ''.isspace() False · Formally, a character is whitespace if the Unicode character database defines its general category is Zs, WS, B, or S. Python’s string class comes with a number of useful additional string methods.
🌐
Javatpoint
javatpoint.com › python-string-isspace-method
Python String | isspace() method with Examples - Javatpoint
Python Function Programs · capitalize() casefold() center(width ,fillchar) count(string,begin,end) encode() endswith(suffix ,begin=0,end=len(string)) expandtabs(tabsize = 8) find(substring ,beginIndex, endIndex) format(value) index(subsring, beginIndex, endIndex) isalnum() isalpha() isdecimal() isdigit() isidentifier() islower() isnumeric() isprintable() isupper() isspace() istitle() isupper() join(seq) ljust(width[,fillchar]) lower() lstrip() partition() replace(old,new[,count]) rfind(str,beg=0,end=len(str)) rindex(str,beg=0,end=len(str)) rjust(width,[,fillchar]) rstrip() rsplit(sep=None, ma