简体   繁体   English

使用Lambda表达式过滤字符串

[英]Using lambda expression to filter a string

How can one use Lambda expression to concatenate all numbers from 1-9 together before operand? 在操作数之前,如何使用Lambda表达式将1-9中的所有数字连接在一起?

if I have a string like 如果我有一个像

Str = "21 2 4 + 21 1"

and want it formatet to: 并希望它格式化为:

newStr = "2124"

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(' ', '')

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. 同样,这看起来非常不安全,并可能导致大量错误。

Just because you asked for a lambda to filter: 只是因为您要过滤的lambda:

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

Just putting this up here for two reasons: 仅仅出于两个原因将其放在这里:

  1. accepted answer doesn't use lambda like OP requested 接受的答案不像请求OP那样使用lambda
  2. OP requested to split on operand (using a + in the example) OP请求拆分操作数(在示例中使用+)

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: 这基本上是相同的方法,但是考虑到其他操作数[+,-,*,/],使用lambda,并且如果字符串中不存在操作数,它也不会失败:

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

A possible way would be to use itertools.takewhile() because it quite literally expresses your intent: " all numbers from 1-9 together before operand? " 一种可能的方法是使用itertools.takewhile()因为它从字面上表达了您的意图:“ 操作数之前的1-9中的所有数字加在一起?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM