0

I have a string that I want to clean using pipe from toolz. But it seems I can't figure out how to apply the str.replace method in the pipeline. Here is an example:

x = '9\xa0766'

from toolz import pipe
import unidecode

# Can do like this, but don't want to use nesting.
int(unidecode.unidecode(x).replace(" ", ""))


# Wan't to try to do like this, with sequence of steps, applying transformations on previous output.
pipe(x, 
  unidecode.unidecode, 
  replace(" ", ""), 
  int
) # DON'T WORK!! 
# NameError: name 'replace' is not defined

More generally, notice that the output of unidecode.unidecode is a string. So I want to be able to apply some string methods to it.

pipe(x, 
  unidecode.unidecode, 
  type
)  # str

Is it possible with pipe?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Retko
  • 332
  • 1
  • 5
  • 14
  • 1
    `replace` isn't a *function*, you'd need e.g. `lambda s: s.replace(...)` or maybe a `partial`. – jonrsharpe Jan 06 '21 at 09:47
  • Thank you for that. `Lambda` is good :). Can you please give an example how would I use `partial` here?? Thank you :) @jonrsharpe – Retko Jan 06 '21 at 10:01

2 Answers2

0

Yes, this is possible with toolz.pipe. Although you can use a lambda, I would use operator.methodcaller as so:

import operator as op
import unidecode
from toolz import pipe

x = '9\xa0766'

# Can do like this, but don't want to use nesting.
int(unidecode.unidecode(x).replace(" ", ""))

# Wan't to try to do like this, with sequence of steps, applying transformations on previous output.
pipe(
    x,
    unidecode.unidecode,
    op.methodcaller("replace", " ", ""),
    int
)
eriknw
  • 286
  • 1
  • 2
0

You could also do the same in slightly different way using lambda

import unidecode
from toolz import pipe

x = '9\xa0766'


pipe(
    x,
    unidecode.unidecode,
    lambda x: x.replace(" ", ""),
    int
)

You could also make it into a function to reuse it elsewhere

import unidecode
from toolz import pipe, compose_left

x = '9\xa0766'

# this becomes a function that can be called
converter = compose_left(
    unidecode.unidecode,
    lambda x: x.replace(" ", ""),
    int
)


result = converter(x)

print(result)
#9766
GRag
  • 1