Yes you can using functools.partial:

from functools import partial

def fun(x, i):
    return x * i

lst1 = [partial(fun, i=i) for i in range(5)]
lst2 = [j(2) for j in lst1]
Answer from AKS on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › map-function-lambda-expression-python-replace-characters
Map function and Lambda expression in Python to replace characters - GeeksforGeeks
July 27, 2022 - In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed ...
Discussions

python - implementing multiple string replace() using lambda function - Stack Overflow
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... More on stackoverflow.com
🌐 stackoverflow.com
python - how to use str.replace in a lambda function in Pandas? - Stack Overflow
I want to use str.replace(), inside a lambda function. More on stackoverflow.com
🌐 stackoverflow.com
python - Lambda function for replacing characters in the string - Stack Overflow
Below is the Python code to replace characters. Can some explain the lambda part? Initially, X is taking "p" and checking if its a1 or a2. where is the swap happening? def replaceUsingMapAndLambda... More on stackoverflow.com
🌐 stackoverflow.com
September 26, 2018
python - Lambda Replace - Stack Overflow
The first occurence of lambda could be replaced with a generator: ... Since sum and string.join can deal with a generator, you can use the generator expression directly as an argument to these functions. ... Save this answer. ... Show activity on this post. ... Generally, generators and comprehensions improve readability, especially if you have to use a lambda to make map or filter work. Moreover, map and lambda don't play well together performance-wise (Python ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
IncludeHelp
includehelp.com › python › map-function-and-lambda-expression-in-python-to-replace-characters.aspx
Map() Function and Lambda Expression in Python to Replace Characters
There will be a string (str), and two characters (ch1, ch2), by using the combination of the map() and Lambda expression, we will replace the characters i.e., ch1 with ch2 and ch2, other characters will remain the same.
Top answer
1 of 3
2

If you really want to you can force a lambda function into it:

print ''.join(map(lambda x: bad_chars.get(x, x), stri))

But really there's absolutely no need to use a lambda function here. All you need is:

print ''.join(bad_chars.get(x, x) for x in stri)

This solution is also linear time (ie O(n)) whereas all the other solutions are potentially quadratic as they involve scanning the entire string to replace each value O(n*m) where m is the size of the bad_chars dict.

Example:

bad_chars= {"\newline":" ","\n": " ", "\b":" ", "\f":" ", "\r":" ", "\t":" ", "\v":" ", "\0x00":" "}
stri = "a \b string\n with \t lots of \v bad chars"
print ''.join(bad_chars.get(x, x) for x in stri)

Ouptut:

a   string  with   lots of   bad chars
2 of 3
1

You can't really do it that easily and if you could a lambda function is still not designed for your use case.

Multiple replacements like that are done using a regular for loop statement, and a lambda is 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 unicode strings (or Python 3), and limit your bad substrings to single characters (i.e. remove "\newline"), you can use the unicode.translate method.

bad_chars = {u"\n": u" ", u"\b": u" ", u"\f": u" ", u"\r": u" ", u"\t": u" ", u"\v": u" ", u"\x00": u" "}
bad_chars_table = dict((ord(k), v) for k, v in bad_chars.iteritems())
translator = lambda s: s.translate(bad_chars_table)
print translator(u"here\nwe\tgo")

2) Use regular expressions:

   translator = lambda s: re.sub(r'[\n\b\f\r\t\v\x00]', ' ', s)

3) You can use reduce which 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.

translator = lambda s: reduce(lambda x, (from, to): x.replace(from, to), bad_chars.iteritems(), s)

As you can see, the last solution is much more difficult to understand than:

def translator(s):
    for original, replacement in bad_chars.iteritems():
        s = s.replace(original, replacement)
    return s

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.

🌐
DataScience Made Simple
datasciencemadesimple.com › home › replace() function in pandas – replace a string in dataframe python
replace() function in pandas - replace a string in dataframe python - DataScience Made Simple
November 15, 2019 - # Replace function in python to replace a substring with another df['Quarters_Replaces'] = map(lambda x: x.replace("q","Q"), df['Quarters']) print df · the occurrences of “q” is replaced with “Q” and the result is stored in ‘Quarters_Replaces’ column ·
Find elsewhere
🌐
Geohernandez
geohernandez.net › python-lambda-and-regex-a-good-team-for-replacing-a-string-using-dictionaries
Python Lambda and Regex – A good team for replacing a string using dictionaries – geohernandez
Remember that regex.sub in this case is able to call a defined function (in our case the Lambda function) for every match delimited for m.group(0) that means an exact match, so in the practice it will internally replace every match into the request string with the respective value of the key contained in the formatted_parameters dictionary.
🌐
Dummies
dummies.com › article › technology › programming-web-design › python › how-to-use-lambda-functions-in-python-264911
How to Use Lambda Functions in Python | dummies
October 9, 2019 - But this is a perfect example of where you could use a lambda function, because the Python function you’re calling, lowercaseof(), does all of its work with just one line of code: return anystring.lower(). When your function can do its thing with a simple one-line expression like that, you can skip the def and the function name and just use this syntax: lambda parameters : expression Replace parameters with one or more parameter names that you make up yourself (the names inside the parentheses after def and the function name in a regular function).
Author:
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.str.replace.html
pandas.Series.str.replace — pandas 3.0.6 documentation
>>> pd.Series(["foo", "fuz", np.nan]).str.replace("f", repr, regex=True) 0 <re.Match object; span=(0, 1), match='f'>oo 1 <re.Match object; span=(0, 1), match='f'>uz 2 NaN dtype: str · Reverse every lowercase alphabetic word: >>> repl = lambda m: m.group(0)[::-1] >>> ser = pd.Series(["foo 123", "bar baz", np.nan]) >>> ser.str.replace(r"[a-z]+", repl, regex=True) 0 oof 123 1 rab zab 2 NaN dtype: str ·
🌐
LWN.net
lwn.net › Articles › 847960
Alternative syntax for Python's lambda [LWN.net]
March 3, 2021 - Python already has both anonymous and named functions. They are spelled with 'lambda' and 'def', respectively. What good would it do us to create an alternate spelling for 'def'? [...] I can sympathize with trying to get a replacement for lambda, because many other languages have jumped on the arrow bandwagon, and few Python first-time programmers have enough of a CS background to recognize the significance of the word lambda.
Top answer
1 of 2
2

An easier way to go would be to use pandas str methods, namely findall (to find all digits using the regex \d+) and join (to join the resulting list of digit substrings together):

>>> df.tel_no.str.findall("\d+").str.join("")

0    18607528792
1    19497228838
Name: tel_no, dtype: object
2 of 2
1

I agree that using regex matching is a good solution to your problem, but I can at least address the problem with your code.

You current code is:

df['tel_no'].apply(lambda x: x.replace(i, '') for i in ['+','-','tel:'])

Python parses this (perhaps surprisingly) as:

df['tel_no'].apply(
    (
        (lambda x: x.replace(i, ''))
        for i in ['+','-','tel:'])
    )
)

That is, you have written a generator comprehension, creating a new anonymous function at each iteration of the loop. You have not created a single anonymous function with a generator comprehension inside it!

Obviously, generators are not callable, which is what caused the error.

Your attempt reflects two additional misunderstandings:

  1. Comprehension syntax cannot be used outside of an actual comprehension. Perhaps you meant to write lambda x: (x.replace(i, '')) for i in ['+','-','tel:']), which would at least be one function that contains a generator comprehension.

  2. String functions like str.replace do not modify the string. They return a new string. See the example below.

s1 = 'hello'
s2 = s1.replace('e', 'f')

# s1 will be unchanged
assert s1 == 'hello'

# s2 will be changed
assert s2 == 'hfllo'

To write this as a function, you would need to use def, not `lambda:

def clean_tel(x):
    for bad_string in ['+', '-', 'tel:']:
        x = x.replace(bad_string, '')
    return x

df['tel_no'].apply(clean_tel)

Or you can omit the loop and write it like this:

df['tel_no'].apply(
    lambda x: x.replace('+', '').replace('-', '').replace('tel:', '')
)
Top answer
1 of 2
1

You can use str.translate for replacing multiple characters at once. str.maketrans helps you create the required mapping:

eSToAvoid = 'éêèÉÊÈ'
textFile.translate(str.maketrans(eSToAvoid, 'e' * len(eSToAvoid)))
2 of 2
0

While the str.replace can only replace one substring with another, re.sub can replace a pattern.

In [55]: eSToAvoid = 'éêèÉÊÈ' 
In [58]: import re 

test cases:

In [61]: re.sub(r'[éêèÉÊÈ]', 'e', 'foobar')                                                                          
Out[61]: 'foobar'
In [62]: re.sub(r'[éêèÉÊÈ]', 'e', eSToAvoid)                                                                         
Out[62]: 'eeeeee'
In [63]: re.sub(r'[éêèÉÊÈ]', 'e', 'testingè,É  foobar  è É')                                                         
Out[63]: 'testinge,e  foobar  e e'

The string replace approach is:

In [70]: astr = 'testingè,É  foobar  è É' 
    ...: for e in eSToAvoid: 
    ...:     astr = astr.replace(e,'e') 
    ...:                                                                                                             
In [71]: astr                                                                                                        
Out[71]: 'testinge,e  foobar  e e'

the replace is applied sequentially to astr. This can't be expressed as a list comprehension (or map). A list comprehensions most naturally replaces a loop that collects its results in a list (with list.append).

There's nothing wrong with the for loop. It's actually faster:

In [72]: %%timeit 
    ...: astr = 'testingè,É  foobar  è É' 
    ...: for e in eSToAvoid: 
    ...:     astr = astr.replace(e,'e') 
    ...:  
    ...:                                                                                                             
1.37 µs ± 8.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [73]: timeit re.sub(r'[éêèÉÊÈ]', 'e', 'testingè,É  foobar  è É')                                                  
2.79 µs ± 15.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [77]: timeit astr.translate(str.maketrans(eSToAvoid, 'e' * len(eSToAvoid)))                                       
2.56 µs ± 14.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

reduce

In [93]: from functools import reduce  
In [96]: reduce(lambda s,e: s.replace(e,'e'),eSToAvoid, 'testingè,É  foobar  è É' )                                  
Out[96]: 'testinge,e  foobar  e e'
In [97]: timeit reduce(lambda s,e: s.replace(e,'e'),eSToAvoid, 'testingè,É  foobar  è É' )                           
2.11 µs ± 32.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

For fun you could also explore some of the idea presented here:

Cleanest way to combine reduce and map in Python

You want to 'accumulate' changes, and to do that, you need some sort of accumulator, something that hangs on to the last replace. itertools has an accumulate function, and Py 3.8 introduced a := walrus operator.

generator

In [110]: def foo(astr, es): 
     ...:     for e in es: 
     ...:         astr = astr.replace(e,'e') 
     ...:         yield astr 
     ...:                                                                                                            
In [111]: list(foo(astr, eSToAvoid))                                                                                 
Out[111]: 
['testingè,É  foobar  è É',
 'testingè,É  foobar  è É',
 'testinge,É  foobar  e É',
 'testinge,e  foobar  e e',
 'testinge,e  foobar  e e',
 'testinge,e  foobar  e e']

Or [s for s in foo(astr, eSToAvoid)] in place of the list(). This highlights that fact that a list comprehension returns a list of strings, even if the strings accumulate the changes.

🌐
Stack Overflow
stackoverflow.com › questions › 73979926 › replace-string-using-map-and-lambda-in-python
dictionary - Replace string using MAP and LAMBDA in Python - Stack Overflow
June 10, 2022 - banks=['BoE','BoC','Fed', 'ECB' ,'RBA','RBNZ'] calendar['event'] = list(map(lambda x : 'Speak' if (any([b in x for b in banks]) and 'Speak' in x) else x, calendar['event'])) ... calendar = pd.DataFrame(columns=['event']) calendar['event'] = ['Speak BoC', 'BoE', 'Speak Q', 'RBNZSpeak'] # Only 1st and 3rd should be replaced by "Speak" banks=['BoE','BoC','Fed', 'ECB' ,'RBA','RBNZ'] calendar['event'] = list(map(lambda x : 'Speak' if (any([b in x for b in banks]) and 'Speak' in x) else x, calendar['event'])) print(calendar.event) # 0 Speak # 1 BoE # 2 Speak Q # 3 Speak
🌐
Reddit
reddit.com › r/python › an alternative lambda syntax for python
r/Python on Reddit: An alternative lambda syntax for Python
July 13, 2011 - Python already allows ; as a statement separator, it is conceivable that indentation could be nested in expressions. Eg: map( mylist, lambda x:( # note lambda appearing at start of a line, to set block indentation if x > 2: return 2 else: return x))