From f585163ece68e592d42d5ada76444482bb89e268 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luiz=20Ot=C3=A1vio?= Date: Wed, 28 Dec 2022 09:28:02 -0300 Subject: [PATCH] =?UTF-8?q?string.Template=20para=20substituir=20vari?= =?UTF-8?q?=C3=A1veis=20em=20textos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- aula183.py | 40 ++++++++++++++++++++++++++++++++++++++++ aula183.txt | 7 +++++++ 2 files changed, 47 insertions(+) create mode 100644 aula183.py create mode 100644 aula183.txt diff --git a/aula183.py b/aula183.py new file mode 100644 index 0000000..3f52052 --- /dev/null +++ b/aula183.py @@ -0,0 +1,40 @@ +# string.Template para substituir variáveis em textos +# doc: https://docs.python.org/3/library/string.html#template-strings +# Métodos: +# substitute: substitui mas gera erros se faltar chaves +# safe_substitute: substitui sem gerar erros +# Você também pode trocar o delimitador e outras coisas criando uma subclasse +# de template. +import locale +import string +from datetime import datetime +from pathlib import Path + +CAMINHO_ARQUIVO = Path(__file__).parent / 'aula183.txt' + +locale.setlocale(locale.LC_ALL, '') + + +def converte_para_brl(numero: float) -> str: + brl = 'R$ ' + locale.currency(numero, symbol=False, grouping=True) + return brl + + +data = datetime(2022, 12, 28) +dados = dict( + nome='João', + valor=converte_para_brl(1_234_456), + data=data.strftime('%d/%m/%Y'), + empresa='O. M.', + telefone='+55 (11) 7890-5432' +) + + +class MyTemplate(string.Template): + delimiter = '%' + + +with open(CAMINHO_ARQUIVO, 'r') as arquivo: + texto = arquivo.read() + template = MyTemplate(texto) + print(template.substitute(dados)) diff --git a/aula183.txt b/aula183.txt new file mode 100644 index 0000000..3a475d1 --- /dev/null +++ b/aula183.txt @@ -0,0 +1,7 @@ +Prezado(a) %nome, + +Informamos que sua mensalidade será cobrada no valor de %{valor} no dia %data. Caso deseje cancelar o serviço, entre em contato com a %empresa pelo telefone %telefone. + +Atenciosamente, + +%{empresa},