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
Release: 2024-11-27 01:20:10
Original
848 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template