简体   繁体   中英

Replacing symbols using list comprehension

I want to simplify replacing specific characters of a string in-situ - with a list comprehension. Attempts so far simply return a list of strings - each list item with each character replaced from the check string.

Advice / solutions?

Inputs:

reveal = "password"
ltrTried = "sr"

Required Output:

return = "**ss**r*"

Getting:

('**ss****', '******r*')

If you want to do this using a list comprehension, you'd want to replace it letter by letter like this:

reveal = "".join((letter if letter in ltrFound else "*") for letter in reveal)

Notice that

  • We're iterating over your reveal string, not your ltrFound list (or string).
  • Each item is replaced using the ternary operator letter if letter in ltrFound else "*" . This ensures that if the letter in reveal is not in ltrFound , it will get replaced with a *.
  • We end by joining together all the letters.

Just for fun, here's a different way to do this immutably, by using a translation map.

If you wanted to replace everything that was in ltrFound , that would be easy:

tr = str.maketrans(ltrFound, '*' * len(ltrFound))
print(reveal.translate(tr))

But you want to do the opposite, replace everything that's not in ltrFound . And you don't want to build a translation table of all of the 100K+ characters that aren't s . So, what can you do?

You can build a table of the 6 characters that aren't in s but are in reveal :

notFound = ''.join(set(reveal) - set(ltrFound)) # 'adoprw'
tr = str.maketrans(notFound, '*' * len(notFound))
print(reveal.translate(tr))

The above is using Python 3.x; for 2.x, maketrans is a function in the string module rather than a classmethod of the str class (and there are a few other differences, but they don't matter here). So:

import string
notFound = ''.join(set(reveal) - set(ltrFound)) # 'adoprw'
tr = string.maketrans(notFound, '*' * len(notFound))
print(reveal.translate(tr))

try this

re.sub("[^%s]"%guesses,"*",solution_string)

assuming guesses is a string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM