meaz0r
meaz0r

Reputation: 35

Using lambda expression to filter a string

How can one use Lambda expression to concatenate all numbers from 1-9 together before operand?

if I have a string like

Str = "21 2 4 + 21 1"

and want it formatet to:

newStr = "2124"

Upvotes: 1

Views: 1887

Answers (5)

emvee
emvee

Reputation: 4449

A possible way would be to use itertools.takewhile() because it quite literally expresses your intent: "all numbers from 1-9 together before operand?"

from itertools import takewhile
# extract all characters until the first operator
def snip(x):
    return takewhile(lambda x: x not in "+-*/", x)

# extract just the digits from the snipped string and
# make a string out of the characters
# **EDIT** filter expression changed to let _only_ digits
#          1-9 pass ...
def digits(x):
    return ''.join( filter(lambda c: ord('1')<=ord(c)<=ord('9'), snip(x)) )

Proof of the pudding:

>>> print digits(" 1 22 hello + 3")
122

Upvotes: 0

AChampion
AChampion

Reputation: 30258

Just because you asked for a lambda to filter:

>>> import re
>>> s = "21 2 4 + 21 1"
>>> ''.join(filter(lambda c: c in '123456789', re.split('[+-/*]', s)[0]))
2124

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49318

Why not with a regular expression?

import re
s = "21 2 4 + 21 1"
new_s = re.match(r'([\d ]+)[-+/*]', s).group(1).replace(' ', '')

Or with string methods?

s = "21 2 4 + 21 1"
new_s = s.split('+')[0].replace(' ', '')

Upvotes: 2

iLoveTux
iLoveTux

Reputation: 3625

Just putting this up here for two reasons:

  1. accepted answer doesn't use lambda like OP requested
  2. OP requested to split on operand (using a + in the example)

This is basically the same method, but takes into account additional operands [+, -, *, /], uses a lambda and it won't fail if operand doesn't exist in the string:

import re
s = ["12 3 65 + 42", "1 8 89 0 - 192", "145 7 82 * 2"]
map(lambda x: re.split("[\+\-\*\/]", x)[0].replace(" ", ""), s)

will output

['12365', '18890', '145782']

Upvotes: 0

Ilian Iliev
Ilian Iliev

Reputation: 3236

The simplest answer is to just replace all spaces with empty string:

"21 2 4 + 21 1".replace(' ', '')  # DO NOT DO THIS

While actually the good answer is to check how you get the data and whether you can process it before. Also this one looks terribly insecure and can lead to tons of errors.

Upvotes: 0

Related Questions