Python find substring in list

Finding substring in the list

I am learning python by looking and also trying to solve interview questions. In the following question and solution is provided. Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. Example 1: Input: «abab» Output: True Explanation: It’s the substring «ab» twice. Example 2: Input: «aba» Output: False

def repeatedSubstringPattern2(self, str): """ :type str: str :rtype: bool """ if not str: return False ss = (str + str)[1:-1] print ss return ss.find(str) != -1 

My question is even though aba is listed as a False example, but looking at the solution it gives me a sense that it is true. Any idea?? What I am missing?

 ss = (aba +aba)[1:-1] --> abaaba[1:-1] --> baaba baaba.find(aba) != -1 --> true?? 

Unrelated to your question, but if you’re learning python you should really learn python 3 instead of python 2.

Читайте также:  Php убрать все знаки препинаний

If you’re coming from another language then camelCase will stand out a lot. See PEP8. You’re also clearly using python 2 where support will be discontinued soon

You’ll have a better programming language, with a better standard library, and it won’t reach end-of-life in 3 years like python 2 will. The question is really not «What’s the advantage of learning python 3»; the question is «What reason is there to still learn python 2?».

Источник

Find a string in a List in Python

Python Find String In List

There are three ways to find a string in a list in Python. They’re as follows:

  1. With the in operator in Python
  2. Using list comprehension to find strings in a Python list
  3. Using the any() method to find strings in a list
  4. Finding strings in a list using the filter and lambda methods in Python

Let’s get right into the individual methods and explore them in detail so you can easily implement this in your code.

1. Using the ‘in’ operator to find strings in a list

In Python, the in operator allows you to determine if a string is present a list or not. The operator takes two operands, a and b , and the expression a in b returns a boolean value.

If the value of a is found within b , the expression evaluates to True , otherwise it evaluates to False .

Here, ret_value is a boolean, which evaluates to True if a lies inside b , and False otherwise.

Here’s an example to demonstrate the usage of the in operator :

a = [1, 2, 3] b = 4 if b in a: print('4 is present!') else: print('4 is not present')

To make the process of searching for strings in a list more convenient, we can convert the above into a function. The following example illustrates this:

def check_if_exists(x, ls): if x in ls: print(str(x) + ' is inside the list') else: print(str(x) + ' is not present in the list') ls = [1, 2, 3, 4, 'Hello', 'from', 'AskPython'] check_if_exists(2, ls) check_if_exists('Hello', ls) check_if_exists('Hi', ls)
2 is inside the list Hello is inside the list Hi is not present in the list

The in operator is a simple and efficient way to determine if a string element is present in a list. It’s the most commonly used method for searching for elements in a list and is recommended for most use cases.

2. Using List Comprehension to find strings

Let’s take another case, where you wish to only check if the string is a part of another word on the list and return all such words where your word is a sub-string of the list item.

List comprehensions can be a useful tool to find substrings in a list of strings. In the following example, we’ll consider a list of strings and search for the substring “Hello” in all elements of the list.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

We can use a list comprehension to find all elements in the list that contain the substring “Hello“. The syntax is as follows:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] matches = [match for match in ls if "Hello" in match] print(matches)

We can also achieve the same result using a for loop and an if statement. The equivalent code using a loop is as follows:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] matches = [] for match in ls: if "Hello" in match: matches.append(match) print(matches)

In both cases, the output will be:

['Hello from AskPython', 'Hello', 'Hello boy!']

As you can observe, in the output, all the matches contain the string Hello as a part of the string. Simple, isn’t it?

3. Using the ‘any()’ method

The any() method in Python can be used to check if a certain condition holds for any item in a list. This method returns True if the condition holds for at least one item in the list, and False otherwise.

For example, if you wish to test whether ‘AskPython’ is a part of any of the items of the list, we can do the following:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] if any("AskPython" in word for word in ls): print('\'AskPython\' is there inside the list!') else: print('\'AskPython\' is not there inside the list')

In the above example, the condition being checked is the existence of the string «AskPython» in any of the items in the list ls . The code uses a list comprehension to iterate over each item in the list and check if the condition holds.

If the condition holds for at least one item, any() returns True and the first if statement is executed. If the condition does not hold for any item, any() returns False and the else statement is executed.

'AskPython' is there inside the list!

4. Using filter and lambdas

We can also use the filter() method on a lambda function, which is a simple function that is only defined on that particular line. Think of lambda as a mini function, that cannot be reused after the call.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] # The second parameter is the input iterable # The filter() applies the lambda to the iterable # and only returns all matches where the lambda evaluates # to true filter_object = filter(lambda a: 'AskPython' in a, ls) # Convert the filter object to list print(list(filter_object))

We do have what we expected! Only one string matched with our filter function, and that’s indeed what we get!

Conclusion

We have seen that there are various ways to search for a string in a list. These methods include the in operator, list comprehensions, the any() method, and filters and lambda functions. We also saw the implementation of each method and the results that we get after executing the code. To sum up, the method you use to find strings in a list depends on your requirement and the result you expect from your code. It could be a simple existence check or a detailed list of all the matches. Regardless of the method, the concept remains the same to search for a string in a list.

References

Источник

Check if List contains a substring in Python

In this article, we will discuss different ways to check if a list contains a substring or not in Python.

Table Of Contents

Introduction

Suppose we have a list of strings. Something like this,

Now we want to check if any string in this list contains a substring – “is” or not. Here, the string “this” in list contains the substring “is”, so yes this list contains the given substring.

There are different ways to check if list contains a substring or not. Let’s discuss them one by one.

Frequently Asked:

Check if list contains a substring using any() function

Iterate over all strings in list, and for each string, check if it contains the given substring or not. If a string contains the given substring then the conditional expression will evaluate to True, otherwise it will evaluate to False. Pass all the resultant values to the any() function, to check if any expression is evaluating to True or not.

The any() function in Python, accepts a sequence of boolean values, and returns True if any value in this boolean list evaluates to True. So, in this case if any() function returns True, it means list has a string that contains the given substring.

Let’s see an example. Here, we will check if any string in this list contains a substring – “is” or not.

# List of strings listOfStrs = ["why", "where", "how", "this", "what"] # A Substring subStr = "is" # check if any string in list contains the given substring if any(subStr in elem for elem in listOfStrs): print('Yes, List contains the substring') else: print('No, List does not contains the substring')
Yes, List contains the substring

Yes, there is atleast a string in the list that contains the given substring.

Check if list contains a substring using List comprehension

Filter the list using List comprehension, and select only those strings which contains the given substring. If the length of this filtered list is more than 0, then it means that list has a string that contains the given substring. Let’s see an example. Here, we will check if any string in this list contains a substring – “is” or not.

# List of strings listOfStrs = ["why", "where", "how", "this", "what"] filteredList = [elem for elem in listOfStrs if "is" in elem] # check if any string in list contains the given substring if len(filteredList) > 0: print('Yes, List contains the substring') else: print('No, List does not contains the substring')
Yes, List contains the substring

Yes, there is atleast a string in the list that contains the given substring.

Check if list contains a substring using a For Loop

Iterate over all the strings in a list using a for loop, and for each string, check if the given substring exists in that string or not. As soon as, it finds a string like that, break the loop. Let’s see an example. Here, we will check if any string in this list contains a substring – “is” or not.

# List of strings listOfStrs = ["why", "where", "how", "this", "what"] # A Sub String subStr = "is" result = False # check if any string in list contains the given substring for elem in listOfStrs: if subStr in elem: result = True break if result: print('Yes, List contains the substring') else: print('No, List does not contains the substring')
Yes, List contains the substring

Yes, there is atleast a string in the list that contains the given substring.

Check if list contains a substring using filter() and Lambda functions

Using the filter() function, and a lambda expression, select only those strings which contains the given substring. If the length of this filtered list is more than 0, then it means that list has a string that contains the given substring. Let’s see an example. Here, we will check if any string in this list contains a substring – “is” or not.

# List of strings listOfStrs = ["why", "where", "how", "this", "what"] # A Sub String subStr = "is" # check if any string in list contains the given substring filteredList = list(filter(lambda elem: subStr in elem, listOfStrs)) if len(filteredList) > 0: print('Yes, List contains the substring') else: print('No, List does not contains the substring')
Yes, List contains the substring

Yes, there is atleast a string in the list that contains the given substring.

Summary

We learned about different ways to check if a list of strings contain a substring or not.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Оцените статью