:PROPERTIES:
:ID:       8b686fdd-2abd-459d-8d8d-0c57915de8fb
:mtime:    20220528112853
:ctime:    20220528110814
:END:
#+title: String

* Méthode /str.translate/
La méthode /str.translate/ permet d'appliquer une table de substitution à la chaine de caractères :
#+BEGIN_SRC python :results output
translation_dict = {ord('a'): ord('A'), ord('b'): "BBB", ord('c'): None}
print(f'{"aaa bbb ccc".translate(translation_dict) = }')
#+END_SRC
#+RESULTS:
: "aaa bbb ccc".translate(translation_dict) = 'AAA BBBBBBBBB '

* La méthode de classe /str.maketrans/
La méthode de classe /str.maketrans/ simplifie la création des tables de translation utilisées par /str.stranslate/ en
supprimant la nécessité d'utiliser la fonction ~ord~ :

#+BEGIN_SRC python :results output
# Without str.mktrans
translation_dict = {ord("0"): "1", ord("1"): "0"}
print(f'{"001011010101001".translate(translation_dict) = }')

# With str.maketrans (single argument)
translation_dict = str.maketrans({'0': '1', '1': '0'})
print(f'{"001011010101001".translate(translation_dict) = }')

# With str.maketrans (two arguments)
translation_dict = str.maketrans("01", "10")
print(f'{"001011010101001".translate(translation_dict) = }')
print(f'{"#0F45cd".translate(str.maketrans("abcdef", "ABCDEF")) = }')
#+END_SRC

#+RESULTS:
: "001011010101001".translate(translation_dict) = '110100101010110'
: "001011010101001".translate(translation_dict) = '110100101010110'
: "001011010101001".translate(translation_dict) = '110100101010110'
: "#0F45cd".translate(str.maketrans("abcdef", "ABCDEF")) = '#0F45CD'

Le dernier argument de /str.maketrans/ permet de lister les caractères à remplacer par ~None~, à supprimer :
#+BEGIN_SRC python :results output
print(f'{"#0F45cd".translate(str.maketrans("abcdef", "ABCDEF", "#")) = }')
#+END_SRC

#+RESULTS:
: "#0F45cd".translate(str.maketrans("abcdef", "ABCDEF", "#")) = '0F45CD'

* Références
 * [[https://mathspp.com/blog/pydonts/string-translate-and-maketrans-methods][String translate and maketrans methods - Pydon't]]

