Python Forum
Doubling every second letter.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Doubling every second letter.
#1
Hello!
I have to create a program, which will be doubles every second letter. Foe example:
input:Tom has cat.
output: Toom hhass caat.
I wrote this cod :
def double(s):
    return ''.join(x * (y% 2 + 1)
    for y, x in enumerate(s))

s=input("text:")
print(double(s))
I have problem, because this program counts whitespace.How to fix it?
Reply
#2
One way is to use slice to deduct count of whitespaces from index.

Below it presented as one-liner, but I think that conventional nested representation will make it more readable.

>>> a = 'Tom has cat'
>>> ''.join([v if v == ' ' or (i - a[:i+1].count(' ')) % 2 == 0 else v * 2 for i, v in enumerate(a)])
Toom hhass caat
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020