Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a question. If I have a string, for example:
str1 = 'Wazzup1'
and numbers:
nums = '1234567890'
I need a code that will look into str1 and tell me if it has any number(not all of them). Please help.
Use any and a generator expression:
any(x in nums for x in str1)
Below is a demonstration:
>>> str1 = 'Wazzup1'
>>> nums = '1234567890'
>>> any(x in nums for x in str1)
True
>>>
Note that the above is for when you have a custom set of numbers to test for. However, if you are just looking for digits, then a cleaner approach would be to use str.isdigit:
>>> str1 = 'Wazzup1'
>>> any(x.isdigit() for x in str1)
True
>>>
Use the any function, which returns a Boolean which is true iff at least one of the elements in the iterable is true.
string = 'Wazzup1'
result = any(c.isdigit() for c in string)
print(result) # True
As most Python programmers will tell you, the most concise way to do this is using:
any(x in nums for x in str1)
However, if you're new to Python or need a better grasp of the basics of string manipulation, then you should learn how to do this using more fundamental tools.
You can access the individual elements of a string, list, tuple, or any other iterable in Python using square brackets around an index. The characters of a string are indexed starting from 0 (e.g. "hello"[0] gives "h").
Using a for loop, the solution is easier to understand for a Python newbie than the above-mentioned any solution:
result = False
for i in range(len(str1)):
if str1[i] in nums:
result = True
A Python for loop can also iterate directly over the elements of the string:
result = False
for x in str1:
if x in nums:
result = True
In the first code snippet in this post, the expression x in nums for x in str1 uses Python's list comprehension feature. This goes through every element x of str1 and finds the result of x in nums. any(x in nums for x in str1) returns True if (and only if) at least one of these results is True (meaning a numerical digit is in str1). This is much like the second for loop example given in this post, and many Python programmers choose this option because it is concise and still understandable by other Python programmers.
You can use any() and string.digits to check whether the string contain a digit:
import string
if any(x in string.digits for x in str1):
pass
You could also use a regular expression:
>>> str1 = 'Wazzup1'
>>> import re
>>> bool(re.search(r'\d', str1))
True
Note: there might be a difference in how c.isdigit(), c in nums, int(c) and \d define what is a digit due to locale or Unicode.
Related
This question already has answers here:
Check if multiple strings exist in another string
(17 answers)
Closed 2 years ago.
str1 = 'Thank you very much. It was really great help for me'
str2 = 'Yes, I am'
str3 = 'No, It wasn`t'
arr = ['it', 'no', 'jack']
if str1 in arr => true
if str2 in arr => false
if str3 in arr => true
i don't care upper or lower.
i want to check that i saved array and check string value if there is a word.
how can i check it?
i tried
print(arr in str)
but error occored
'in ' requires string as left operand, not list
somebody help me
If I understand correctly what is your desired test here:
print(any(s.lower() in str1.lower() for s in arr))
print(any(s.lower() in str2.lower() for s in arr))
print(any(s.lower() in str3.lower() for s in arr))
Try any method :)
print(any(i in arr for i in str1.lower())
print(any(i in arr for i in str2.lower())
print(any(i in arr for i in str3.lower())
As the error suggests, it is the other way around:
print(str1 in arr)
print(str2 in arr)
print(str3 in arr)
Consider looking at the traceback and try to make more sense out of it. Most issues can be debugged quite easily from the traceback and googling on the specific issue.
However, looks like you are trying to check any word inside arr lies in your particular string str, you can do this:
print(any(s in str1 for s in arr))
Since you're apparently only trying to match words but not punctuations, it's easiest to use a regex pattern with desired words joined as an alternation pattern, enclosed with word boundary checks on both ends:
import re
re.search(rf"\b({'|'.join(arr)})\b", str1, re.I)
This returns a truthy value for str1 and str3, and a falsey value for str2, from your sample inputs.
Just do this if you don't care about upper or lower:
print(str1 in arr, str2 in arr, str3 in arr)
I recently came across some python code I don't understand completely.
s = "abcdef"
x = "bde"
it = iter(s)
print all(c in it for c in x)
I understand that this code checks if x is a subsequence of s. Can someone explain or point me towards an article that explains what's exactly happening at c in it. What is calling the next method of iterator it?
It’s good to start with reading the documentation for the built-in function all():
Return True if all elements of the iterable are true (or if the iterable is empty).
That means that c in it for c in x is a “generator expression”: it produces values. The values it produces are of the boolean expression c in it (see the in operator) for all characters c in string x.
Here, the in operator is responsible for advancing the iterator. Note, however, that the True result is probably lucky. The iterator it can advance only once and because x = "bde" contains the letters in the same sequence as they appear in s = "abcdef", the whole expression works out to the expected result True. Reverse x = "edb" and the expression is False because the iterator is exhausted.
In Scala I could test if a string has a capital letter like this:
val nameHasUpperCase = name.exists(_.isUpper)
The most comprehensive form in Python I can think of is:
a ='asdFggg'
functools.reduce(lambda x, y: x or y, [c.isupper() for c in a])
->True
Somewhat clumsy. Is there a better way to do this?
The closest to the Scala statement is probably an any(..) statement here:
any(x.isupper() for x in a)
This will work in using a generator: from the moment such element is found, any(..) will stop and return True.
This produces:
>>> a ='asdFggg'
>>> any(x.isupper() for x in a)
True
Or another one with map(..):
any(map(str.isupper,a))
Another way of doing this would be comparing the original string to it being completely lower case:
>>> a ='asdFggg'
>>> a == a.lower()
False
And if you want this to return true, then use != instead of ==
There is also
nameHasUpperCase = bool(re.search(r'[A-Z]', name))
I am a beginner, and I am trying to find out the number of vowels in each word in a string. So for instance, if I had "Hello there WORLD", I want to get an output of [2, 2, 1].
Oh, and I am using Python.
I have this so far
[S.count(x) in (S.split()) if x is 'AEIOUaeiou']
where S="Hello there WORLD"
but it keeps saying error. Any hints?
x is 'AEIOUaeiou'
This tests whether x is precisely the same object as 'AEIOUaeiou'. This is almost never what you want when you compare objects. e.g. the following could be False:
>>> a = 'Nikki'
>>> b = 'Nikki'
>>> a is b
False
Although, it may be True as sometimes Python will optimise identical strings to actually use the same object.
>>> a == b
True
This will always be True as the values are compared rather than the identity of the objects.
What you probably want is:
x in 'AEIOUaeiou'
Obviously, S in S.count and S in S.split cannot be the same S. I suggest using more semantic names.
>>> phrase = 'Hello there WORLD'
>>> [sum(letter.casefold() in 'aeiouy' for letter in word) for word in phrase.split()]
[2, 2, 1]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
def my_isdigit(str):
if digit in str >0 and str is int:
print "True"
else:
print "False"
I am trying to create a function that does what isdigit does i.e. returns true if all characters in the string are digits and there is at least one character, false otherwise. Every time I try to use this it tells me "digit" is not defined. I am confused as to what it is asking me to change... Help would be greatly appreciated!
The function looks at each character and only returns True if all are digits:
digits = '0123456789'
def isdigit(inputstring):
if not inputstring: return False
for char in inputstring:
if char not in digits:
return False
return True
Or make use of string comparisons:
def isdigit(inputstring):
if not inputstring: return False
for char in inputstring:
if not '0' <= char <= '9':
return False
return True
Your function is, unfortunately, way off. You don't define digit, nor do you loop over the characters of str. int is a type; strings (even individual characters) are not integers; and a string like -42 can be converted to an integer but '-42'.isdigit() returns False because '-' is not a digit.
#Martijn Pieters suggested how to fix your version; here for completeness is a more "pythonic" (and efficient) approach to the problem.
def my_isdigit(str):
return all('0'<=c<='9' for c in str)
You can use regular expressions
def my_isdigit(str):
return re.search("[^\d]", str) is None
Since there's some questions here are some simple tests:
print my_isdigit("02211")
> True
print my_isdigit("022x01")
> False
print my_isdigit("a02201")
> False