简体   繁体   中英

What is the most efficient way of comparring 2 strings in Python

I'm looking for the most efficient way to compare two strings, and I'm not sure which is better: == or in . Or is there some other way to do it that is more efficient that either of these?

Edit: I'm trying to check for equality

They do different things.

== tests for equality:

"tomato" == "tomato"  # true
"potato" == "tomato"  # false
"mat"    == "tomato"  # false

in tests for substring , and can be considered a (probably) more efficient version of str.find() != -1 ):

"tomato" in "tomato"  # true
"potato" in "tomato"  # false
"mat"    in "tomato"  # true  <-- this is different than above

In both cases, they're the most efficient ways available of doing what they do. If you're using them to compare whether two strings are actually equal, then of course strA == strB is faster than (strA in strB) and (strB in strA) .

Please define "comparing".

If you want to know if 2 strings are equal, == is the simplest way.

If you want to know if 1 string contains another, in is the simplest way.

If you want to know how much they overlap, considering gaps, you need complicated algorithms. How about a thick book on algorithms? (This is similar to comparing genetic sequences. I think a book on Bioinformatics algorithms would be very useful too. Anyhow, this case is way too complicated for Stack Overflow.)

EDIT:

For equality stick with "==". It's in Python to do its job.

== in Python is there for comparison purpose, while "in" has a wider definition (contains which includes comparison). Generally, precise and clear purpose constructs are the most optimized ones for doing the targeted job, because indirect constructs are generally based on simple and direct constructs, which should make == better in comparison context and less error-prone.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM