I have tried to searched it but no specific answer.
I would like to identify the string I want to use depending on the characters appears before it.
What I like to do is, For example:
def check_if_char_appears(input_string):
substring_list = ['aa', 'bb', 'dd', 'ef']
for i in substring_list:
if i appears right before 'cake':
return True
return False
result: Condition1:
input_string = 'aacake'
check_if_char_appears(input_string)
is True
Condition2:
input_string = 'aakkcake'
check_if_char_appears(input_string)
is False
found the java solution could do the funcion "if i appears before 'cake':"
str.matches("i*(?<!\\.)cake.*");
but I dont know how to do with python the this function.. could some one kindly help me with this (or tell me how to look this up in google?)
Thanks!
for simple case like yours.
substring_list = ['aa', 'bb', 'dd', 'ef']
for i in substring_list:
if "{}cake".format(i) in input_string:
return True
Using regex
matches = re.match(r'.*(aa|bb|dd|ef)cake.*', your_str)
if matches:
# do whatever you want
If you want nothing after the cake
matches = re.match(r'.*(aa|bb|dd|ef)cake', your_str)
if matches:
# do whatever you want
You can use regex here. you can make regex on the go like.
substring_list = ['aa', 'bb', 'dd', 'ef']
if re.match(r"({})cake".format("|".join(substring_list)), input_string):
return True
long answer:
def check_if_char_appears(input_string):
substring_list = ['aa', 'bb', 'dd', 'ef']
sub_string_re = "|".join(substring_list) # 'aa|bb|dd|ef'
re_string = r"({})cake".format(sub_string_re) # (aa|bb|dd|ef)cake
if re.match(re_string, input_string):
return True
return False
input_string = 'aacake'
print(check_if_char_appears(input_string))
input_string = 'aakkcake'
print(check_if_char_appears(input_string))
out:
True
False
There is a regex module in python ( https://docs.python.org/3.6/library/re.html )
That should do exactly the same thing just with
import re
m = re.search("i*(?<!\\.)cake.*", your_string)
for match in m:
print(m)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.