You are using the for loop wrong.
This takes each character in the string, assigns it to x, and prints it:
for x in 'aabfh':
print (x)
This takes each character in the string, assigns it to list1[i], and prints it:
for list1[i] in 'aabfh':
print(list1[i])
In your code, if you look at list1, you will find that it has been changed to ['h', 'h', 'h'] because that's what you told it to do (or at least as many h's as "some condition" will allow).
Answer from Kenny Ostrom on Stack OverflowYou are using the for loop wrong.
This takes each character in the string, assigns it to x, and prints it:
for x in 'aabfh':
print (x)
This takes each character in the string, assigns it to list1[i], and prints it:
for list1[i] in 'aabfh':
print(list1[i])
In your code, if you look at list1, you will find that it has been changed to ['h', 'h', 'h'] because that's what you told it to do (or at least as many h's as "some condition" will allow).
Your for loop raise NameError. you can't access to elements of a list in for loop like that. change it to this one to print your desired output:
for char in str1:
if char in list1:
print(char)
a
a
b
for printing its position you can use index:
for char in str1:
if char in list1:
print(list1.index(char))
0
0
1
Given:
s = 'ABCDEFGHIJKLMNOP'
targets = 'CDE','XYZ','JKL'
With loops:
for t in targets:
for i in range(len(s) - len(t) + 1):
for j in range(len(t)):
if s[i + j] != t[j]:
break
else:
print(s[i:])
break
else:
print(t,'does not exist')
Pythonic way:
for t in targets:
i = s.find(t)
if i != -1:
print(s[i:])
else:
print(t,'does not exist')
Output (in both cases):
CDEFGHIJKLMNOP
XYZ does not exist
JKLMNOP
Here's a concise way to do so:
s = "ABCDEFGHIJKLMNOP"
if "CDE" in s:
print s[s.find("CDE")+len("CDE"):]
else:
print s
Prints:
FGHIJKLMNOP
The caveat here is of course, if the sub-string is not found, the original string will be returned.
Why do this? Doing so allows you to check whether or not the original string was found or not. As such, this can be conceptualized into a simple function (warning: no type checks enforced for brevity - it is left up to the reader to implement them as necessary):
def remainder(string, substring):
if substring in string:
return string[string.find(substring)+len(substring):]
else:
return string
Finding values in a string using for loops in Python 3 - Stack Overflow
What is the most efficient way to find substrings in strings?
Using while loops to find a character in a string
How do I check if string contains all substrings in list?
You could try
if all([val in string for val in list]):
Which checks the truth of each check and returns True only if all are True. Otherwise you're looking at a loop (or if your lists get really big a generator).
Videos
Hello,
There are several ways to find substrings in string, You could use substring in string you could use string.index(substring), or you could use string.find(substring) or even use regex.
I'm trying to understand if there is a significant difference between them for my use case, which is finding people names in article titles for example:
I want to check if Leonardo DiCaprio is in Leonardo DiCaprio gets called out for boarding superyacht: ‘eco-hypocrite’
What I usually do is:
def is_substring_in_string(substring: str, string: str):
#same thing as before but on the article title.
string_alphanumeric = ''.join(e for e in string if e.isalnum()).lower()
return substring in string_alphanumeric
def main():
names = ["Harrison Ford","Leonardo DiCaprio","Eddie Murphy","Bruce Willis","Will Smith"]
#removes unwanted charecters such as !@#$%^&*() etc and converts to lower case
names_alnum_lower = [''.join(e for e in x if e.isalnum()).lower() for x in names]
article_title = "Leonardo DiCaprio gets called out for boarding superyacht: eco-hypocrite"
for idx, lower_name in enumerate(names_alnum_lower):
if is_substring_in_string(lower_name,article_title):
print(f"Actor Name: '{names[idx]}' is in article title '{article_title}'")
if __name__ == '__main__':
main()Imagine there are a bunch of articles and people's names. Is this method acceptable or will I be better off using regex or something else?