Use the str.isspace() method:
Return
Trueif there are only whitespace characters in the string and there is at least one character,Falseotherwise.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.
Use the str.isspace() method:
Return
Trueif there are only whitespace characters in the string and there is at least one character,Falseotherwise.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.
str.isspace() returns False for a valid and empty string
>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]
Therefore, checking with not will also evaluate None Type and '' or "" (empty string)
>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]
Isspace function in python - Stack Overflow
Python isspace function - Stack Overflow
python - Check if string is None, empty or has spaces only - Stack Overflow
using isspace() to check if it is a single word
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.
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(' ','')
You want non whitespace, so you should use not
def get_num_of_non_WS_characters(s):
count = 0
for char in s:
if not char.isspace():
count += 1
return count
>>> get_num_of_non_WS_characters('hello')
5
>>> get_num_of_non_WS_characters('hello ')
5
For completeness, this could be done more succinctly using a generator expression
def get_num_of_non_WS_characters(s):
return sum(1 for char in s if not char.isspace())
As an alternative you could also simple do:
def get_num_of_non_WS_characters(s):
return len(''.join(s.split()))
Then
s = 'i am a string'
get_num_of_non_WS_characters(s)
will return 10
This will also remove tabs and new line characters:
s = 'i am a string\nwith line break'
''.join(s.split())
will give
'iamastringwithlinebreak'
The only difference I can see is doing:
not s or not s.strip()
This has a little benefit over your original way that not s will short-circuit for both None and an empty string. Then not s.strip() will finish off for only spaces.
Your s is None will only short-circuit for None obviously and then not s.strip() will check for empty or only spaces.
It is also possibile to do something like the following:
strings = [ None, " Hello +1 ", " ", "World", " +1, +2" ]
for item in strings:
is_empty = not (item or '').strip() # <--- takes '' over None
print(f"item: '{item}' --> is empty: {is_empty}")
# output:
# item: 'None' --> is empty: True
# item: ' Hello ' --> is empty: False
# item: ' ' --> is empty: True
# item: 'World' --> is empty: False
The accepted answer is possibly better, this solution only has the advantage that it supports other string related functions as well, like:
size = len( item or '' )
if (item or '').startswith('hello'):
print(f"item has: {(item or '').count("+1")}")
This implementation may still fail if the item is not None and not string, eg. integer, ...
See also:
- Introducing a Safe Navigation Operator in Python
- PEP 505 – None-aware operators
Hi, there. I need help with isspace()
What I want: print True if it is a single word
However: print False even though it is a single word
Like this:
x = 'dssdsdsdsdsds' check: bool = x.isspace() print(check) #False
I would appreciate it if anyone could give me a hint. Thanks in advance!!
def tt(w):
if ' ' in w:
print 'space'
else:
print 'no space'
>> tt('b ')
>> space
>> tt('b b')
>> space
>> tt('bb')
>> no space
I am in train, sorry for not explaining.. cannot type much..
You are using isspace which says
str.isspace()
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.