如何解决Python提取从索引开始到字符的字符串
说我的传入字符串略有不同:
-
" 1 |r|=1.2e10 |v|=2.4e10"
-
" 12 |r|=-2.3e10 |v|=3.5e-04"
-
"134 |r|= 3.2e10 |v|=4.3e05"
我需要提取数字(例如1.2e10、3.5e-04等)...,所以我想从“ | r |”的末尾开始并抓住所有字符,直到其后的“”(空格)。与“ | v |”
相同我一直在寻找可以实现以下目标的东西: 从字符串中提取一个子字符串,该字符串从索引开始并以特定字符结尾。 但是还没有发现遥不可及的东西。 想法?
注意:添加了新的场景,这是导致大量抓挠的场景...
解决方法
为了保持其优雅和通用,让我们利用split
:
- 首先,我们将''划分为令牌
- 然后我们发现它是否具有等号并解析键值
import re
sabich = "134 |r| = 3.2e10 |v|=4.3e05"
parts = sabich.split(' |')
values = {}
for p in parts:
if '=' in p:
k,v = p.split('=')
values[k.replace('|','').strip()] = v.strip(' ')
# {'r': '3.2e10','v': '4.3e05'}
print(values)
这可以转换为单线:
import re
sabich = "134 |r| = 3.2e10 |v|=4.3e05"
values = {t[0].replace('|','').strip() : t[1].strip(' ') for t in [tuple(p.split('=')) for p in sabich.split(' |') if '=' in p]}
# {'|r|': '1.2e10','|v|': '2.4e10'}
print(values)
,
您可以使用正则表达式来解决它。
public function agregar_pagos()
{
$this->load->library("EscPos.php");
$nombre_impresora = "ImpresoraCMD";
try {
$connector = new Escpos\PrintConnectors\WindowsPrintConnector($nombre_impresora);
$printer = new Escpos\Printer($connector);
$printer->text("\n"."Body Effect" . "\n");
$printer->text("Plaza Midtown Jalisco,Local 53,"."\n"."Italia Providencia Guadalajara,Jal.");
$printer->text("Teléfono: (442) 145 23 76" . "\n");
$printer->text("\n");
$printer->text("RECIBÍ:\n");
$printer->text("LA CANTIDAD DE:\n");
$printer->text("QUINCE MIL TREINTA PESOS CON 0/0 CENTAVOS M.N\n");
$printer->text("\n");
$printer->text("Pago de servicios\n");
$printer->text("-----------------------------"."\n");
$printer->text("\n");
$printer->text("SUBTOTAL: $15,030.00\n");
$printer->text("IVA: $0.00\n");
$printer->text("TOTAL: $15,030.00\n");
$printer->feed(3);
$printer->cut();
$printer->pulse();
$printer->close();
} catch (Exception $e) {
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
}
}
输出
import re
strings = [
" 1 |r|=1.2e10 |v|=2.4e10"," 12 |r|=-2.3e10 |v|=3.5e-04"
]
out = []
pattern = r'(?P<name>\|[\w]+\|)=(?P<value>-?\d+(?:\.\d*)(?:e-?\d*)?)'
for s in strings:
out.append(dict(re.findall(pattern,s)))
print(out)
如果要将字符串转换为数字
[{'|r|': '1.2e10','|v|': '2.4e10'},{'|r|': '-2.3e10','|v|': '3.5e-04'}]
输出
out = []
pattern = r'(?P<name>\|[\w]+\|)=(?P<value>-?\d+(?:\.\d*)(?:e-?\d*)?)'
for s in strings:
# out.append(dict(re.findall(pattern,s)))
out.append({
name: float(value)
for name,value in re.findall(pattern,s)
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。