user3247775
user3247775

Reputation: 33

Python: replace every letter except the nth letters in a string with a period(or another character)

So I have looked at the replace every nth letter and could not figure out the reverse. I started with this and quickly realized it would not work:

s = input("Enter a word or phrase: ")
l = len(s)

n = int(input("choose a number between 1 and %d: " %l))

print (s[0] + "." * (n-1)+ s[n]+ "." * (n-1) + s[n*2])

any help would be appreciated.

Upvotes: 3

Views: 647

Answers (5)

Don
Don

Reputation: 17636

My tricky solution (I'll let you add comments):

s = 'abcdefghijklmnopqrstuvwxyz'
n = 3
single_keep_pattern = [False] * (n - 1) + [True]
keep_pattern = single_keep_pattern * ( len(s) / n + 1)
result_list = [(letter if keep else '.') for letter, keep in zip(s, keep_pattern)]
result = ''.join(result_list)

print result

gives:

..c..f..i..l..o..r..u..x..

Upvotes: 0

lvc
lvc

Reputation: 35089

Build from what you already know. You know how to find every nth character, and your result string will have all of those in it and no other character from the original string, so we can use that. We want to insert things between those, which is exactly what the str.join method does. You've already worked out that what to insert is '.' * n-1. So, you can do this:

>>> s = "abcdefghi"
>>> n = 3
>>> ('.' * (n-1)).join(s[::n])
'a..d..g'

The only trick is that you need to account for any characters after the last one that you want to leave in place. The number of those is the remainder when the highest valid index of s is divided by n - or, (len(s) - 1) % n. Which gives this slightly ugly result:

>>> ('.' * (n-1)).join(s[::n]) + '.' * ((len(s) - 1) % n)
'a..d..g..'

You probably want to use variables for the two sets of dots to help readability:

>>> dots = '.' * (n - 1)
>>> end_dots = '.' * ((len(s) - 1) % n)
>>> dots.join(s[::n]) + end_dots
'a..d..g..'

Upvotes: 0

venpa
venpa

Reputation: 4318

You can use reduce following way:

>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> n=3
>>> print reduce(lambda i,x: i+x[1] if (x[0]+1)%n else i+".", enumerate(s), "")
ab.de.gh.jk.mn.pq.st.vw.yz
>>> print reduce(lambda i,x: i+"." if (x[0]+1)%n else i+x[1], enumerate(s), "")
..c..f..i..l..o..r..u..x..

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

If the user enters 3, I'm assuming you want to replace the third, sixth, ninth...letter, right? Remember that indices are counted from 0:

>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> remove = 3
>>> "".join(c if (i+1)%remove else "." for i,c in enumerate(s))
'ab.de.gh.jk.mn.pq.st.vw.yz'

Or, if you meant the opposite:

>>> "".join("." if (i+1)%remove else c for i,c in enumerate(s))
'..c..f..i..l..o..r..u..x..'

Upvotes: 1

Hyperboreus
Hyperboreus

Reputation: 32449

Let s be the original string and n the position not to be replaced.

''.join (c if i == n else '.' for i, c in enumerate (s) )

Upvotes: 1

Related Questions