Reputation:
If I have a string like this: ABCDE
I want to read two characters at a time (AB then CD) and remove the remaining characters (E) which cannot be read in tuples or in two's. How would I remove those characters?
I have this code below so far:
s = 'ABCDE'
for (first, second) in zip(s[0::2], s[1::2]):
if not first or not second:
if first:
s.replace(first, '')
continue
else:
s.replace(second, '')
continue
print first, second
print s
This code prints (A B
C D
) which is good but I want to remove that extra E
in the for loop which I am trying to do with the if statement. I check if the either the first
or second
variable of the tuple is an empty string and then remove whichever one isn't an empty string from the original s
variable.
This above code doesn't seem to work. Does anyone have a different suggestion or how I can improve this?
Upvotes: 2
Views: 488
Reputation: 7706
str = "ABCDE"
for i, k in zip(str[::2], str[1::2]):
print(i + k)
Outputs:
AB
CD
Upvotes: 0
Reputation: 16730
If you want to remove the last character in case the string's length is odd:
word = "ABCDE"
if len(word) % 2 == 1:
word = word[:-1]
Now if you want to read the characters two at a time, here is a more instinctive way:
for i in range(len(word) // 2):
print(word[2*i:2*i+2])
The latter will even drop the last character for you.
Upvotes: 3