-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaula183.py
40 lines (30 loc) · 1.05 KB
/
aula183.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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))