1

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"
0

5 Answers 5

2

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(' ', '')
Sign up to request clarification or add additional context in comments.

4 Comments

This looks super. Can you tell me what the r' in the regex means?
The regexp is terrible. If there is no + sign in the string it will throw an exception. You should check for match before trying to get the group.
@IlianIliev - good point about the operator; fixed. I just chained the methods for convenience - a quick way to show that a successful re.match returns an object with a group method, which returns a string. For the string method version, a simple for opr in '+-*/': would handle the other operators.
@meaz0r - the r'... denotes a raw string. We actually want to send those literal backslashes to the regular expression parser, so raw strings allow us to do this without a lot of backslash escaping.
0

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.

Comments

0

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']

2 Comments

The lambda is a little contrived in your example :) And I don't believe you need to escape special characters in [ ]
OK, that's true, I tried to make a better example for using a lambda, also I fixed a typo where I used s in the lambda when I should have used x. I thought so too (about escaping special characters in [ ]), but I get error: bad character range when I don't.
0

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

Comments

0

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

5 Comments

I would be cautious saying things like "most correct", as this is a matter of opinion. BTW the OP excluded 0 from the list of digits.
Agreed. When it comes to that ... OP hasn't exactly specified what is valid input and what not. What to do if a non-whitespace non-digit character is found before the operator?
@AChampion: Specifically, what should the code do if a digit '0' is found before the operator? I adjusted the filter expression to only extract digits 1-9
@havee I assume like everything else, discard them, though I'm really wondering if the OP meant what they wrote.
I have the same doubts :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.