Python Check array item in string [duplicate] - python

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)

Related

if statement with square bracket [duplicate]

This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 2 years ago.
I would like to know what if the difference with and without square bracket
Here is my code without square bracket in the if statement, which answer is correct.
a=[3,90,3,7,8,100]
if sum(a)<100:
a.append(2)
print(a)
While if I put the square bracket, it will be wrong, Can anyone explain it to me?
a=[3,90,3,7,8,100]
if [sum(a)<100]:
a.append(2)
print(a)
So when you use the square brakets, python check whether the list is empty rather then the value inside the list.
This is always interpreted as True, thus the wrong results.
Example to emphasize it:
l = [True]
if l:
print("test")
l = [False]
if l:
print("test")
Both cases will print "test".
a=[3,90,3,7,8,100] # in python lists are denoted by square brackets
if sum(a)<100: # Here sum(a) means sum([3,90,...]) it's a list and it can add all.
a.append(2) # append means adding new element at end of the list a
print(a)
a=[3,90,3,7,8,100]
if [sum(a)<100]: # here the condition will be always true because [True] is not empty
a.append(2)
print(a)
The check is if the list is empty. See the below for explanation
>>> [sum(a)<100]
[False]
>>> if [False]:
... print('hello')
...
hello
>>> if []:
... print('hello')
...
>>>
if [sum(a)<100]: can be understand as: if [False]:. And [False] will be interpreted as True in if statement (see this). So if statement will be execute.

If substring in string, when substring has multiple values

I know there is a way to work around it, but I want to understand the underlying logic as to why this doesn't work.
It's a very simple statement, and it only returns as True when the first substring in the "or list" is shown.
for i in list:
if (substring1 or substring2 or substring3) in string:
print(string + " found!")
What am I missing here? I would think the or conditions would equal true if any substring was found in the string. As is, I'm only coming up as true if substring1 is found in string, and no substring2 or substring3.
substring1 or substring2 or substring3
Assuming that substring1 is not the empty string, this expression evaluates to substring1 because substring1 is truthy. This is then checked to see if it's in string. The other substrings have no effect on the statement.
In other words, the ors are evaluated before the in, and the or evaluates to the first truthy value it finds (this is called short-circuiting). You can't use in that way to check whether multiple substrings are in a string.
You want:
substring1 in string or substring2 in string or substring3 in string
Or:
substrings = (substring1, substring2, substring3)
if any(s in string for s in substrings):
>>> string = 'hello'
>>> s1 = 'he'
>>> s2 = 'll'
>>> s3 = 'o'
>>> (s1 or s2 or s3)
'he'
>>> 'he' in string
True
The problem here is that you are first evaluating (s1 or s2 or s3) which will give you s1 if s1 does not evaluate to false. In a boolean context, empty strings evaluate to false:
>>> s1 = ''
>>> (s1 or s2 or s3)
'll'
What you want is s1 in string or s2 in string or s3 in string, this will return true if at least one of the substrings is in the string.
Its because python uses lazy evaluation... for example...
def error():
raise ArithmeticError
print "nothing" or error()
Will Print "nothing" because it evaluates to True in python code does not check error, which would ordinarily raise an error and stop the script from continuing...
print False or error() #raises error and breaks script
(substring1 or substring2 or substring3) #returns the first true value
The correct code should be
for i in list:
if (substring1 in i ) or (substring2 in i) or (substring3 in i):
print(i + " found!")
The above code can find substring when they have multiple values.
(substring1 or substring2 or substring3)
This expression will return the first item in brackets that is not null.
For example, if subtring1 is not null, it will return the value of substring1.
When substring1 is not null,
(substring1 or substring2 or substring3)
equals to
substring1
You probably want any:
if any(substr in string for substr in substrs):
# At least one match

How to find out if str has any number [closed]

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.

<function>(str1, str2) calling them separately

First off, this IS homework, so I am not expecting any direct answers. I need to take two strings defined by a function (semordnilap(str1, str2)) and I need to see if they are equal when one is reversed. I was wondering if I can call these separately out of the function with semordnilap(str1[0:1) == semordnilap(str2[-1]) I tried this a few ways and I must not be thinking about it correctly, plus of course there is the kicker of trying to do this recursively. Any advise or direction would be helpful.
def semordnilap(str1, str2):
'''
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap
False otherwise.
'''
if len(str1) != len(str2):
return False
if len(str1) <= 1 or len(str2) <= 1:
return False
if semordnilap(str1[0]) != semordnilap(str2[-1]):
return False
else:
return True
This is what I have so far, getting error of TypeError: semordnilap() takes exactly 2 arguments (1 given)
Given two strings str1 and str2, the easiest way to compare if one is equal to the reverse of the other is by using slicing:
str1 = 'racecar'
str2 = 'racecar'
str1 == str2[::-1]
Out[57]: True
Which is really just checking if str1 is a palindrome (i.e. a reverse of itself).
If you really want to use recursion, you also want to be using slicing: check if str1[0] == str2[-1], and then recursively call your function on str1[1:] and str2[:-1].
The [::-1] syntax is extended slicing syntax, which is valid for strings as well as lists and other sequences.
To reverse a string you use 'this is a string'[::-1].
[::-1] Is slice notation which says include everything from the start to the end of the string but do it in reverse.
'abcdefghijk'[6:1:-2] outputs 'gec' because it goes from the 6th index (starting with 0) up to but not including the first index, in reverse steps of 2.
Read up more on slice notation:Explain Python's slice notation, http://docs.python.org/2.3/whatsnew/section-slices.html
def semordnilap(str1, str2):
if str1 == str2[::-1]: return True
else: return False
One way to do it recursively:
def semordnilap(str1, str2):
if not (len(str1) or len(str2)): return True
if not (len(str1) and len(str2)): return False
if str1[0] != str2[-1]: return False
return semordnilap(str1[1:], str2[:-1])
The first line checks if both strings are empty (0 evaluates to False, any other number is True). len(str1) returns the length as an integer.
Then it checks if only one of the strings is empty in which case they are not equal.
Then it checks if the first letter is the same as the last letter.
Then it repeats the process with the each string (minus the first letter of str1 and minus the last letter of str2). It goes until one of the base cases is reached. The base case is what is returned. So it will only return True when then first letter was equal to the last letter each round until both strings ran out of characters at the same time.

Filtering Characters from a String [duplicate]

This question already has answers here:
Remove specific characters from a string in Python
(26 answers)
Closed 9 years ago.
I need to make a function that takes two strings as imnput and returns a copy of str 1 with all characters from str2 removed.
First thing is to iterate over str1 with a for loop, then compare to str2, to accomplish subtraction I should create a 3rd string in which to store the output but I'm a little lost after that.
def filter_string(str1, str2):
str3 = str1
for character in str1:
if character in str2:
str3 = str1 - str2
return str3
This is what I've been playing with but I don't understand how I should proceed.
Just use str.translate():
In [4]: 'abcdefabcd'.translate(None, 'acd')
Out[4]: 'befb'
From the documentation:
string.translate(s, table[, deletechars])
Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.
If -- for educational purposes -- you'd like to code it up yourself, you could use something like:
''.join(c for c in str1 if c not in str2)
Use replace:
def filter_string(str1, str2):
for c in str2:
str1 = str1.replace(c, '')
return str1
Or a simple list comprehension:
''.join(c for c in str1 if c not in str2)

Categories

Resources