Nicholas Rogers
Nicholas Rogers

Reputation: 109

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.

Upvotes: 0

Views: 484

Answers (1)

xnx
xnx

Reputation: 25518

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).

Upvotes: 1

Related Questions