Reputation: 11
I have strings representing a DNA sequence and its complement and I am searching them for reverse palindromes.
The slice
seq1[i:z]
works great, but
seq2[i:z:-1]
prints nothing and returns nothing.
Further, seq[i:z][::-1]
works fine in all cases, but is this normal for string slices?
Upvotes: 1
Views: 112
Reputation: 176938
If you're stepping backwards through an iterable (i.e. step
is negative), you need to swap the order of the start
and end
values so that start > end
:
>>> seq = 'abcde'
>>> seq[1:4:-1]
''
>>> seq[4:1:-1]
'edc'
Otherwise, you'll get back an empty string (or empty list or empty tuple).
Do note that seq[4:1:-1]
does not produce the same result as seq[1:4][::-1]
however. The former starts at index 4
, moves backwards and stops before index 1
, whereas the latter starts at index 1
, moves forward, stops before index 4
and then reverses the slice.
Instead we have for an iterable seq
and for integers i < j
:
seq[i:j][::-1] == seq[j-1:i-1:-1]
Upvotes: 6
Reputation: 4035
For palindroms,
a=input("entry something: ")
if a==a[::-1]:
print ("It is a palindrom.")
So if a's reverse equal to a, it will print its a palindrom.
Upvotes: 0