简体   繁体   中英

How can I count character matches in a string in python?

Eg:

String 1: Can We Live (feat. Cece Rogers) [Joke Instrumental Mix] 
String 2: Can We Live (feat. Cece Rogers) Joke Instrumental Mix 

 Match count = 53

Have read this: Character match count between strings in perl

Want to do this pythonically.

To answer the question asked in your heading, you can get a count of the number of matching characters in two strings with:

In [1]: s1 = 'Can We Live (feat. Cece Rogers) [Joke Instrumental Mix]'
In [2]: s2 = 'Can We Live (feat. Cece Rogers) Joke Instrumental Mix'

In [3]: if len(s1) > len(s2):     # swap strings so that s1 is shortest
   .....:     s1, s2 = s2, s1
   .....:     

In [4]: sum(c1==s2[i] for i, c1 in enumerate(s1))
Out[4]: 32

But this may not be a good enough measure of similarity for your purposes. Look into the Levenshtein distance and its implementation in the distance module instead if that is the case.

EDIT: @Veedrac is perfectly correct: a simpler, one-line solution without the swap is:

sum(c1 == c2 for c1, c2 in zip(s1, s2))

( zip ignores items in the longer sequence).

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