Posts: 124
Threads: 74
Joined: Apr 2017
Sep-16-2019, 12:11 PM
(This post was last modified: Sep-16-2019, 01:16 PM by SriRajesh.)
Hi,
I have two strings
str1 = 'ABCdef'
str2 = 'ABCdaf'
now I want to know which position (character) is different.
Desired output is 4
in str1: e
same position is str2: a
Posts: 4,220
Threads: 97
Joined: Sep 2016
If you want to know where the 'e' is, you use index: st1.index('e') . If you want to know what is at that location you use slicing: st1[4] .
Posts: 124
Threads: 74
Joined: Apr 2017
I don't know before hand,
1. check is two strings equal or not
2. If not equal. then get which position is not equal
Posts: 4,220
Threads: 97
Joined: Sep 2016
Posts: 1,950
Threads: 8
Joined: Jun 2018
(Sep-16-2019, 12:40 PM)SriRajesh Wrote: I don't know before hand,
1. check is two strings equal or not
2. If not equal. then get which position is not equal
This is not reasonable approach. Why should you process strings twice? When are strings not equal? Strings are not equal if their corresponding characters don't match. So you can in one iteration compare corresponding characters and get indices of non-equal ones.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Posts: 124
Threads: 74
Joined: Apr 2017
1 2 3 4 5 6 7 8 9 |
str1 = 'ABCdef'
str2 = 'ABCdaf'
u = zip (str1,str2)
print (u)
for i,j in u:
if i = = j:
print (i, '--' ,j)
else :
print (i, ' ' ,j)
|
I want to get the positions where inequality
Posts: 1,950
Threads: 8
Joined: Jun 2018
(Sep-16-2019, 01:17 PM)SriRajesh Wrote: I want to get the positions where inequality
Maybe something along these lines:
1 2 3 4 5 6 7 |
>>> for i, pair in enumerate ( zip ( 'spam' , 'eggs' )):
... print (i, pair)
...
0 ( 's' , 'e' )
1 ( 'p' , 'g' )
2 ( 'a' , 'g' )
3 ( 'm' , 's' )
|
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
|