I’ve found tons of solutions doing exactly what I’m trying to do WITHOUT lambda…but I’m learning lambda today…
I have a string stri and I’m trying to replace some characters in stri that are all stored in a dictionary.
bad_chars={"\newline":" ","\n": " ", "\b":" ", "\f":" ", "\r":" ", "\t":" ", "\v":" ", "\0x00":" "} and then I want to print stri out all pretty and empty of all of these ugly characters. My current code print’s stri many many times.
format_ugly = lambda stri: [ stri.replace(i,j) for i,j in bad_chars.iteritems()]
Is there a way to make it print once, and with only 1 lambda function?
You can’t really do it that easily and if you could a
lambdafunction is still not designed for your use case.Multiple replacements like that are done using a regular
forloop statement, and alambdais limited to a single expression. If you have to use a function, use a normal function – it’s entirely equivalent to a lambda function except that it’s not limited to a single expression.If you really must know how to do it in a single expression, you have three choices:
1) If you use
unicodestrings (or Python 3), and limit your bad substrings to single characters (i.e. remove"\newline"), you can use theunicode.translatemethod.2) Use regular expressions:
3) You can use
reducewhich can be used to reduce a sequence using a binary operation, essentially repeatedly calling a function of two arguments with the current value and an element of the sequence to get the next value.As you can see, the last solution is much more difficult to understand than:
And both solutions do the same thing. It’s often better to program for the end, not for the means. For an arbitrary problem a comprehensible single-expression solution wouldn’t exist at all.