This question already has answers here:
Check if multiple strings exist in another string
(17 answers)
Closed 7 years ago.
To check if a string contains a substring, one can use "in" like so:
if "abc" in str:
print("yay")
And to check if a string contains one of two substrings one can use "or" like so:
if "abc" in str or "def" in str:
print("yay")
My question is whether or not python has a way to simplify that into something like this:
if "abc" or "def" in str:
print("yay")
I know this won't work as intended because it will always evaluate to true. (Python will check for at least one of the two statements, either
"abc"
"def" in str
being true and "abc" will always evaluate to true)
Having said that, is there anyway to check for such a condition other than this, rather verbose, method:
if "abc" in str or "def" in str:
print("yay")
if any(word in sentence for word in {"abc", "def"}):
print("yay")
Put them in an array and do:
if any(x in word for x in a):
This has been answered here Check if multiple strings exist in another string
If your question is like whether there is a way, to check whether any string in given list of strings exist in a bigger string . We can use the any() function along with generator expressions for that.
Example -
>>> s = "Hello World Bye Abcd"
>>> l = ["Hello","Blah"]
>>> l1 = ["Yes","No"]
>>> any(li in s for li in l)
True
>>> any(li in s for li in l1)
False
Related
This question already has answers here:
Find common characters between two strings
(5 answers)
Closed 2 months ago.
I have a string of text
hfHrpphHBppfTvmzgMmbLbgf
I have separated this string into two half's
hfHrpphHBppf,TvmzgMmbLbgf
I'd like to check if any of the characters in the first string, also appear in the second string, and would like to class lowercase and uppercase characters as separate (so if string 1 had a and string 2 had A this would not be a match).
and the above would return:
f
split_text = ['hfHrpphHBppf', 'TvmzgMmbLbgf']
for char in split_text[0]:
if char in split_text[1]:
print(char)
There is probably a better way to do it, but this a quick and simple way to do what you want.
Edit:
split_text = ['hfHrpphHBppf', 'TvmzgMmbLbgf']
found_chars = []
for char in split_text[0]:
if char in split_text[1] and char not in found_chars:
found_chars.append(char)
print(char)
There is almost certainly a better way of doing this, but this is a way of doing it with the answer I already gave
You could use the "in" word.
something like this :
for i in range(len(word1) :
if word1[i] in word2 :
print(word[i])
Not optimal, but it should print you all the letter in common
You can achieve this using set() and intersection
text = "hfHrpphHBppf,TvmzgMmbLbgf"
text = text.split(",")
print(set(text[0]).intersection(set(text[1])))
You can use list comprehension in order to check if letters from string a appears in string b.
a='hfHrpphHBppf'
b='TvmzgMmbLbgf'
c=[x for x in a if x in b]
print(' '.join(set(c)))
then output will be:
f
But you can use for,too. Like:
a='hfHrpphHBppf'
b='TvmzgMmbLbgf'
c=[]
for i in a:
if i in b:
c.append(i)
print(set(c))
This question already has answers here:
What is the best approach in python: multiple OR or IN in if statement?
(3 answers)
Closed 1 year ago.
I have a string variable (mystring). In a while loop the user can input the content of the string and I want to break the loop when it contains the letter 'a' and the letter 'b'. I tried the following:
mystring = ''
while 'a' or 'b' not in mystring:
mystring = input('write:')
the while loop works perfect if I use just one of the letters (no or statement).
If I check mystring e.g. after inputting 'abacjihgea' using
'a' and 'b' in mystring
it returns True. Shouldn't it break the while loop then?
Unfortunately I can't seem to fix this problem.
You should check separately and with an and condition
while ('a' not in mystring) and ('b' not in mystring) :
mystring=input()
A cleaner method is using set and intersection for multiple chars
while not {'a','b'}.issubset(mystring):
mystring=input()
You can use Regular expression as well.
If order of letters is certain e.g. a followed by b then a.*b otherwise (a.*b|b.*a).
import re
mystring = ''
while not re.search('(a.*b|b.*a)',mystring):
mystring = input('write:')
This question already has answers here:
Check if a string contains a number
(20 answers)
Closed 7 years ago.
I am a newbie in Python. I am making a program where I take a input from user and check if any number is inside in the string. I am checking it by taking it in a variable. Is it not correct to check via a VARIABLE?
user_string=input("Enter the Word:")
print (user_string)
for index in (0,9):
number=str(index) #Typecasting Int to String
if number in user_string: #Check if Number exist in the string
print ("yes")
output:
Enter the Word:helo2
helo2
You can use the string method isdigit() on each character in a generator expression within any. This will short-circuit upon finding the first numeric character (if one is present)
>>> user_string = 'helo2'
>>> any(i.isdigit() for i in user_string)
True
>>> user_string = 'hello'
>>> any(i.isdigit() for i in user_string)
False
Look at your for-loop. You are looping over a tuple (0,9). So actually you are only testing for 0 and 9. Use range(10) instead.
More elegant, to get the numbers inside your string, you can use sets:
import string
print 'yes' if set(string.digits).intersection(user_string) else 'no'
This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 7 years ago.
I know in python there is a way to turn a word or string into a list using list(), but is there a way of turning it back, I have:
phrase_list = list(phrase)
I have tried to change it back into a string using repr() but it keeps the syntax and only changes the data type.
I am wondering if there is a way to turn a list, e.g. ['H','e','l','l','o'] into: 'Hello'.
Use the str.join() method; call it on a joining string and pass in your list:
''.join(phrase)
Here I used the empty string to join the elements of phrase, effectively concatenating all the characters back together into one string.
Demo:
>>> phrase = ['H','e','l','l','o']
>>> ''.join(phrase)
'Hello'
Using ''.join() is the best approach but you could also you a for loop. (Martijn beat me to it!)
hello = ['H','e','l','l','o']
hello2 = ''
for character in hello:
hello2 += character
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to replace a string in a function with another string in Python?
I want to enter any string with any type of character, and if the character is an alphabet, I want to replace it with "^" and get it printed.
For example, if my input is replace('text-here'), I should get the output as "^^^^-^^^^".
I've tried using the following statement, but it just prints whatever my input was. Please help!
def replace(string):
for x in range(len(string)):
string.replace(string[x],"^")
print(string)
I'm new to python, and don't know complex stuff. Please give me easy-to-understand answers. Thanks!
>>> text = 'text-here'
>>> ''.join('^' if c.isalpha() else c for c in text)
'^^^^-^^^^'
I think this is easy to understand but just in case here is code that shows what it does more simply:
>>> def replace(text):
new_text = ''
for c in text:
if c.isalpha():
new_text += '^'
else:
new_text += c
return new_text
>>> replace(text)
'^^^^-^^^^'
You could use Python's Regular Expressions library.
Like so,
import re
re.sub('\w', '^', 'text-here')
# Outputs: "^^^^-^^^^"
That's because string is immutable. string.replace(string[x],"^") returns a new object.
Modify
string.replace(string[x],"^")
to
string = string.replace(string[x],"^")
and it will work as expected.
Now that your question is on "but it just prints whatever my input was", I would like to tell you that the method str.replace will return a new string instead of to replace the string in place.
>>> a = "foo"
>>> a.replace("foo","bar")
'bar'
>>> a
'foo'
So you need to do string = string.replace(...)