Home >Backend Development >Python Tutorial >How Can I Efficiently Check if a String Matches Any of Many Strings in Python?

How Can I Efficiently Check if a String Matches Any of Many Strings in Python?

DDD
DDDOriginal
2024-11-27 01:20:10851browse

How Can I Efficiently Check if a String Matches Any of Many Strings in Python?

Comparing a String to Numerous Items in Python

Challenge:

Suppose we have a string, termed 'facility,' and a collection of valid strings. The objective is to ascertain whether 'facility' coincides with any of these legitimate strings in an efficient manner.

Solution:

To avoid the conventional approach of using multiple 'if' statements, consider leveraging a set.

Code:

accepted_strings = {'auth', 'authpriv', 'daemon', '(any number of additional strings)'}

if facility in accepted_strings:
    # Execute desired actions

Benefit:

Testing for containment within a set has an average time complexity of O(1). This method is significantly more efficient than using a series of 'if' statements when dealing with large lists of valid strings.

The above is the detailed content of How Can I Efficiently Check if a String Matches Any of Many Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn