15-03-2019
This commit is contained in:
355
docs/Programmation/Python/Python.md
Normal file
355
docs/Programmation/Python/Python.md
Normal file
@@ -0,0 +1,355 @@
|
||||
# Python 3
|
||||
|
||||
|
||||
|
||||
1. collections:
|
||||
1. [liste](liste.md)
|
||||
2. [dictionnaire](dictionnaire.md)
|
||||
3. [tuple](tuple.md)
|
||||
4. [set](set.md)
|
||||
2. [class - objet](class.md)
|
||||
3. [date](date.md)
|
||||
4. [fichiers](fichiers.md)
|
||||
5. [fonctions](fonctions.md)
|
||||
6. [fabric-ssh](fabric-ssh.md)
|
||||
7. [regex](regex.md)
|
||||
8. [strings](string.md)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
https://www.tutorialspoint.com/python3/index.htm
|
||||
|
||||
https://www.w3schools.com/python/default.asp
|
||||
|
||||
|
||||
|
||||
#### Instruction de boucles
|
||||
|
||||
##### while:
|
||||
|
||||
```python
|
||||
while n != 1:
|
||||
if n % 2 == 0 : # si un nombre entier modulo 2 vaut 0, il est pair
|
||||
n = n // 2
|
||||
else: # cas où le nombre est impair
|
||||
n = 3*n + 1
|
||||
|
||||
print(n)
|
||||
```
|
||||
|
||||
##### for:
|
||||
|
||||
```python
|
||||
somme = 0
|
||||
for val in range(5): # 0 1 2 3 4
|
||||
somme += val
|
||||
|
||||
print(somme)
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Conditions:
|
||||
|
||||
##### if:
|
||||
|
||||
```python
|
||||
>>> x = 1
|
||||
>>> if x > 5:
|
||||
... x = x + 1
|
||||
... elif x == 5:
|
||||
... x = x + 1000
|
||||
... else:
|
||||
... x = x - 1
|
||||
...
|
||||
>>> x
|
||||
0
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Compréhension de liste:
|
||||
|
||||
```python
|
||||
# Soit une liste:
|
||||
>>> a = [1,4,2,7,1,9,0,3,4,6,6,6,8,3]
|
||||
|
||||
# On veut filtrer les nombres > 5
|
||||
>>> b = []
|
||||
>>> for x in a:
|
||||
... if x > 5:
|
||||
... b.append(x)
|
||||
...
|
||||
>>> b
|
||||
[7, 9, 6, 6, 6, 8]
|
||||
|
||||
# La même chose sur une seule ligne
|
||||
>>> [x for x in a if x > 5]
|
||||
[7, 9, 6, 6, 6, 8]
|
||||
|
||||
```
|
||||
|
||||
```python
|
||||
# Convertir plusueurs chaines en entiers
|
||||
>>> items = ["5", "10", "15"]
|
||||
>>> items = [int(x) for x in items]
|
||||
>>> print(items)
|
||||
[5, 10, 15]
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Collections:
|
||||
|
||||
[liste](liste.md):
|
||||
|
||||
```python
|
||||
>>> liste = [1,2,3]
|
||||
>>> liste
|
||||
[1, 2, 3]
|
||||
|
||||
# modifiable, ordonée
|
||||
```
|
||||
|
||||
[set](set.md):
|
||||
|
||||
```python
|
||||
>>> un_set = {"apple", "banana", "cherry"}
|
||||
>>> un_set
|
||||
{'apple', 'cherry', 'banana'}
|
||||
|
||||
# ni ordonnée, ni indexée
|
||||
```
|
||||
|
||||
[tuple](tuple.md):
|
||||
|
||||
```python
|
||||
>>> un_tuple = ("alpha","beta","gamma")
|
||||
>>> un_tuple
|
||||
('alpha', 'beta', 'gamma')
|
||||
|
||||
# non modifiable, ordonée
|
||||
```
|
||||
|
||||
[dictionnaire](dictionnaire.md):
|
||||
|
||||
```python
|
||||
>>> un_dict = {
|
||||
... "brand": "Ford",
|
||||
... "model": "Mustang",
|
||||
... "year": 1964
|
||||
... }
|
||||
>>> un_dict
|
||||
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
|
||||
|
||||
# modifiable, non ordonée, indexée
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Opérateurs:
|
||||
|
||||
Operateurs relationnels:
|
||||
|
||||
```python
|
||||
<, <=, >, >=, == et !=
|
||||
```
|
||||
|
||||
Opérateurs booléens:
|
||||
|
||||
```python
|
||||
and, or et not
|
||||
```
|
||||
|
||||
|
||||
|
||||
Instruction `pass`:
|
||||
|
||||
```python
|
||||
if x < 0 :
|
||||
pass # TODO compléter le code (cas où x < 0)
|
||||
else :
|
||||
print('traitement du cas où x est positif')
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Fonction (def):
|
||||
|
||||
```python
|
||||
def pgcd(x, y):
|
||||
"""
|
||||
calcule le pgcd de 2 nombres entiers positifs
|
||||
"""
|
||||
while (y > 0):
|
||||
x, y = y, x % y
|
||||
return x
|
||||
|
||||
>>> pgcd(45, 78)
|
||||
3
|
||||
|
||||
# utiliser une liste pour paramètres
|
||||
>>> param = [45, 78]
|
||||
>>> pgcd(*param)
|
||||
3
|
||||
# * => opérateur splat
|
||||
|
||||
# rendre obligatoire uniquement certains paramètres
|
||||
>>> def fiche(prenom, nom, *reste):
|
||||
... return prenom + " " + nom
|
||||
...
|
||||
>>> fiche("john", "doe")
|
||||
'john doe'
|
||||
|
||||
# utiliser un dictionnaire pour paramèttres
|
||||
>>> param = {"prenom": "john", "nom": "doe"}
|
||||
>>> def fiche(**param):
|
||||
... return param["nom"]
|
||||
...
|
||||
>>> fiche(nom="doe")
|
||||
'doe'
|
||||
|
||||
>>> def fiches(prenom="", nom=""):
|
||||
... return "{} {}".format(prenom, nom)
|
||||
...
|
||||
>>> fiches(*param)
|
||||
'prenom nom'
|
||||
>>> fiches(**param)
|
||||
'john doe'
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Importer des fonctions d'autres fichiers
|
||||
|
||||
Le fichier regroupant les fonctions `functions.py` se trouvent dans le même répertoire que le script `test.py`:
|
||||
|
||||
`functions.py`
|
||||
|
||||
```python
|
||||
def x2(x):
|
||||
return x * 2
|
||||
```
|
||||
|
||||
`test.py`
|
||||
|
||||
```python
|
||||
from functions import *
|
||||
|
||||
nb = int(input("Choisissez un nombre : "))
|
||||
print("Vous avez choisi", nb)
|
||||
|
||||
multiplie = x2(nb)
|
||||
print(nb, " x2 = ", multiplie)
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Importer un module:
|
||||
|
||||
L'interpréteur recherche les modules dans
|
||||
|
||||
1. le répertoire courant
|
||||
2. tous les répertoires de la variable `PYTHONPATH`
|
||||
3. dans le chemin par défaut (`/usr/local/lib/python3/`)
|
||||
|
||||
```python
|
||||
import datetime
|
||||
```
|
||||
|
||||
```python
|
||||
# importe uniquement la section time du module datetime
|
||||
from datetime import time
|
||||
```
|
||||
|
||||
```python
|
||||
# importe le module calendar et crée un alias c
|
||||
import calendar as c
|
||||
|
||||
print(c.month_name[1])
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Exécuter un script Python
|
||||
|
||||
```bash
|
||||
$ python /chemin/script.py
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Exceptions (try / except / finally)
|
||||
|
||||
```python
|
||||
>>> a = 0
|
||||
>>> b = 2
|
||||
>>> try:
|
||||
... b/a
|
||||
... print("Ok", b/a)
|
||||
... except:
|
||||
... print("Erreur")
|
||||
...
|
||||
Erreur
|
||||
|
||||
|
||||
>>> try:
|
||||
... b/a
|
||||
... print("Ok", b/a)
|
||||
... except ZeroDivisionError:
|
||||
... print("Erreur: division par 0")
|
||||
... finally:
|
||||
... print("Instructions exécutées quelque soit les erreurs générées")
|
||||
...
|
||||
Erreur: division par 0
|
||||
Instructions exécutées quelque soit les erreurs générées
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### pdb
|
||||
|
||||
pdb est un débugger.
|
||||
|
||||
Ajouter ce qui suit à la ligne à étudier:
|
||||
|
||||
```python
|
||||
import pdb; pdb.set_trace()
|
||||
```
|
||||
|
||||
Le programme s'arrête à la ligne et donne accès à un shell:
|
||||
|
||||
```python
|
||||
\r\nDNT: 1\r\nAccept-Encoding: gzip, deflate\r\n\r\n'
|
||||
> /Users/bruno/PycharmProjects/webserver/serve2.py(23)<module>()
|
||||
-> client_connection.sendall(http_response)
|
||||
(Pdb) l
|
||||
18 Hello, World!
|
||||
19 """
|
||||
20 import pdb;
|
||||
21
|
||||
22 pdb.set_trace()
|
||||
23 -> client_connection.sendall(http_response)
|
||||
24 client_connection.close()
|
||||
[EOF]
|
||||
(Pdb) n
|
||||
TypeError: a bytes-like object is required, not 'str'
|
||||
> /Users/bruno/PycharmProjects/webserver/serve2.py(23)<module>()
|
||||
-> client_connection.sendall(http_response)
|
||||
(Pdb)
|
||||
```
|
||||
|
||||
Les commandes utiles:
|
||||
|
||||
- `l`: Liste quelques lignes de code avant et après là où vous vous trouver. Utile pour se resituer dans le contexte du programme. ‘l’ pour ‘list’.
|
||||
- `n`: Exécute la ligne suivante. Vous pouvez ainsi continuer l’exécution du programme de bout en bout, ligne par ligne, et le tester en entier. ‘n’ pour ‘next’.
|
||||
- `s`: Si votre ligne contient un appel de fonction ou de méthode, rentre dans à l’intérieur. ‘s’ pour ‘step in’.
|
||||
- `r`: Si vous êtes dans une fonction ou une méthode, celà permet d’en sortir et de passer dans le scope du dessus. ‘r’ pour ‘return’.
|
||||
- `unt`: Si vous êtes à la dernière ligne d’une boucle, permet de reprendre l’exécution jusqu’à la sortie de la boucle. ‘unt’ pour ‘until’.
|
||||
- `q`: Quitte brutalement le programme en le faisant crasher. ‘q’ pour ‘quit’.
|
||||
- `c`: Quitte le debugger et continue l’exécution du programme normalement. Tous les changements que vous avez fait dans le code sont pris en compte. ‘c’ pour ‘continue’.
|
||||
|
||||
|
||||
|
||||
70
docs/Programmation/Python/class.md
Normal file
70
docs/Programmation/Python/class.md
Normal file
@@ -0,0 +1,70 @@
|
||||
|
||||
|
||||
# class
|
||||
|
||||
|
||||
|
||||
##### Créer une class:
|
||||
|
||||
```python
|
||||
class MaClass:
|
||||
x = 5
|
||||
```
|
||||
|
||||
##### Créer un objet:
|
||||
|
||||
```python
|
||||
p1 = MaClass()
|
||||
print(p1.x)
|
||||
|
||||
5
|
||||
```
|
||||
|
||||
##### Fonction \__init__()
|
||||
|
||||
La fonction \__init__() est appelée automatiquement chaque fois que la class est utilisée.
|
||||
|
||||
```python
|
||||
class Person:
|
||||
def __init__(self, name, age):
|
||||
self.name = name
|
||||
self.age = age
|
||||
|
||||
p1 = Person("John", 36)
|
||||
|
||||
print(p1.name)
|
||||
print(p1.age)
|
||||
|
||||
John
|
||||
36
|
||||
```
|
||||
|
||||
##### Méthodes:
|
||||
|
||||
```python
|
||||
class Person:
|
||||
def __init__(self, name, age):
|
||||
self.name = name
|
||||
self.age = age
|
||||
|
||||
def myfunc(self):
|
||||
print("Hello my name is " + self.name)
|
||||
|
||||
p1 = Person("John", 36)
|
||||
p1.myfunc()
|
||||
|
||||
Hello my name is John
|
||||
```
|
||||
|
||||
##### Modifier les propiétés de l'objet:
|
||||
|
||||
```python
|
||||
p1.age = 40
|
||||
```
|
||||
|
||||
|
||||
|
||||
```python
|
||||
|
||||
```
|
||||
|
||||
156
docs/Programmation/Python/date.md
Normal file
156
docs/Programmation/Python/date.md
Normal file
@@ -0,0 +1,156 @@
|
||||
# Date
|
||||
|
||||
|
||||
|
||||
On importe le module `datetime`.
|
||||
|
||||
```python
|
||||
from datetime import datetime
|
||||
```
|
||||
|
||||
Obtenir l'heure courante:
|
||||
|
||||
```python
|
||||
>>> maintenant = datetime.now()
|
||||
>>> maintenant
|
||||
datetime.datetime(2019, 3, 2, 6, 57, 24, 532139)
|
||||
|
||||
# datetime(année, mois, jour, heure, minute, seconde, microseconde, fuseau horaire)
|
||||
|
||||
>>> maintenant.year
|
||||
2019
|
||||
>>> maintenant.month
|
||||
3
|
||||
>>> maintenant.day
|
||||
2
|
||||
>>> maintenant.hour
|
||||
6
|
||||
>>> maintenant.minute
|
||||
57
|
||||
>>> maintenant.second
|
||||
24
|
||||
>>> maintenant.microsecond
|
||||
532139
|
||||
>>> maintenant.isocalendar
|
||||
<built-in method isocalendar of datetime.datetime object at 0x104900b70>
|
||||
|
||||
>>> maintenant.date()
|
||||
datetime.date(2019, 3, 2)
|
||||
>>> maintenant.time()
|
||||
datetime.time(6, 57, 24, 532139)
|
||||
```
|
||||
|
||||
Créer une date:
|
||||
|
||||
```python
|
||||
# année, mois, jour sont obligatoires
|
||||
>>> a = datetime(2001, 1, 1)
|
||||
>>> a.year
|
||||
2001
|
||||
```
|
||||
|
||||
Durée:
|
||||
|
||||
```python
|
||||
>>> duree = datetime.now() - datetime(2001, 1, 1)
|
||||
>>> duree
|
||||
datetime.timedelta(days=6634, seconds=26875, microseconds=353545)
|
||||
|
||||
>>> duree.days
|
||||
6634
|
||||
>>> duree.total_seconds()
|
||||
573204475.353545
|
||||
|
||||
```
|
||||
|
||||
Format d'affichage:
|
||||
|
||||
```python
|
||||
>>> maintenant = datetime.now()
|
||||
>>> maintenant
|
||||
datetime.datetime(2019, 3, 2, 7, 50, 30, 756453)
|
||||
|
||||
>>> maintenant_US = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
|
||||
>>> maintenant_US
|
||||
'2019-03-02 07:49:12.627321'
|
||||
|
||||
>>> maintenant_FR = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
|
||||
>>> maintenant_FR
|
||||
'02-03-2019 07:53:05'
|
||||
```
|
||||
|
||||
[Liste des formats](https://docs.python.org/fr/3/library/datetime.html#strftime-and-strptime-behavior)
|
||||
|
||||
### Calendrier:
|
||||
|
||||
```python
|
||||
>>> import calendar
|
||||
```
|
||||
|
||||
```python
|
||||
>>> calendar.mdays # nb de. jours dans le mois
|
||||
[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
|
||||
>>> calendar.isleap(2020) # année bisextile ?
|
||||
True
|
||||
>>> calendar.weekday(1966, 8, 31) # jour précis d'une date (2 => mercredi)
|
||||
2
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Timestamp:
|
||||
|
||||
Récupérer le timestamp courant:
|
||||
|
||||
```python
|
||||
>>> from datetime import datetime
|
||||
>>> import calendar
|
||||
>>> d = datetime.now()
|
||||
>>> ts = calendar.timegm(d.utctimetuple())
|
||||
>>> ts
|
||||
1551516334
|
||||
```
|
||||
|
||||
```python
|
||||
>>> import time
|
||||
>>> ts = time.time()
|
||||
>>> ts
|
||||
1551511030.9611452
|
||||
```
|
||||
|
||||
```python
|
||||
>>> import datetime
|
||||
>>> ts = datetime.datetime.now().timestamp()
|
||||
>>> ts
|
||||
1551511138.821511
|
||||
|
||||
# equivalent
|
||||
>>> from datetime import datetime
|
||||
>>> ts = datetime.now().timestamp()
|
||||
>>> ts
|
||||
1551511979.337509
|
||||
```
|
||||
|
||||
```python
|
||||
import calendar, time
|
||||
>>> ts = calendar.timegm(time.gmtime())
|
||||
>>> ts
|
||||
1551511394
|
||||
```
|
||||
|
||||
Récupérer une date depuis un timestamp:
|
||||
|
||||
```python
|
||||
# heure utc
|
||||
>>> d = datetime.utcfromtimestamp(ts)
|
||||
>>> d
|
||||
datetime.datetime(2019, 3, 2, 8, 53, 3)
|
||||
```
|
||||
|
||||
```python
|
||||
# heure LOCALE
|
||||
>>> e = datetime.fromtimestamp(ts)
|
||||
>>> e
|
||||
datetime.datetime(2019, 3, 2, 9, 53, 3)
|
||||
```
|
||||
|
||||
231
docs/Programmation/Python/dictionnaire.md
Normal file
231
docs/Programmation/Python/dictionnaire.md
Normal file
@@ -0,0 +1,231 @@
|
||||
# Dictionnaire
|
||||
|
||||
|
||||
|
||||
Un dictionnaire est une sorte de liste, mais qui utilise des clés à la place des index.
|
||||
C'est une collection **non ordonnée**, **modifiable** et **indexée**.
|
||||
|
||||
|
||||
|
||||
##### Créer un dictionnaire:
|
||||
|
||||
```python
|
||||
>>> dict = {}
|
||||
|
||||
>>> type(dict)
|
||||
<class 'dict'>
|
||||
```
|
||||
|
||||
```python
|
||||
>>> un_dict = {
|
||||
... "marque": "Ford",
|
||||
... "modele": "Mustang",
|
||||
... "annee": 1964
|
||||
... }
|
||||
>>> un_dict
|
||||
{'marque': 'Ford', 'modele': 'Mustang', 'annee': 1964}
|
||||
```
|
||||
|
||||
```python
|
||||
# Constructor dict()
|
||||
>>> un_dict = dict(marque="Ford", modele="Mustang", annee=1964)
|
||||
>>> un_dict
|
||||
{'marque': 'Ford', 'modele': 'Mustang', 'annee': 1964}
|
||||
```
|
||||
|
||||
##### Accéder à un item:
|
||||
|
||||
```python
|
||||
>>> un_dict = dict(marque="Ford", modele="Mustang", annee=1964)
|
||||
>>> un_dict
|
||||
{'marque': 'Ford', 'modele': 'Mustang', 'annee': 1964}
|
||||
```
|
||||
|
||||
```python
|
||||
>>> x = un_dict["modele"]
|
||||
>>> x
|
||||
'Mustang'
|
||||
```
|
||||
|
||||
```python
|
||||
>>> x = un_dict.get("modele")
|
||||
>>> x
|
||||
'Mustang'
|
||||
```
|
||||
|
||||
##### Récupérer une valeur (get):
|
||||
|
||||
```python
|
||||
>>> dict = {'language': 'python', 'version': '3.7'}
|
||||
>>>
|
||||
>>> dict.get("language")
|
||||
'python'
|
||||
>>> dict.get("os", "pas de clé os")
|
||||
'pas de clé os'
|
||||
```
|
||||
|
||||
##### Modifier une valeur:
|
||||
|
||||
```python
|
||||
>>> un_dict = dict(marque="Ford", modele="Mustang", annee=1964)
|
||||
>>> un_dict["annee"] = 1965
|
||||
>>> un_dict
|
||||
{'marque': 'Ford', 'modele': 'Mustang', 'annee': 1965}
|
||||
```
|
||||
|
||||
##### Y ajouter des valeurs:
|
||||
|
||||
```python
|
||||
>>> dict["language"] = "python"
|
||||
>>> dict["version"] = "3.7"
|
||||
>>> dict
|
||||
{'language': 'python', 'version': '3.7'}
|
||||
```
|
||||
|
||||
##### Vérifier la présence d'une clé (in):
|
||||
|
||||
```python
|
||||
>>> "language" in dict
|
||||
True
|
||||
```
|
||||
|
||||
##### Supprimer une entrée (del):
|
||||
|
||||
```python
|
||||
>>> del dict["version"]
|
||||
>>> print(dict)
|
||||
{'language': 'python'}
|
||||
```
|
||||
|
||||
##### Supprimer une entrée (pop):
|
||||
|
||||
```python
|
||||
>>> dict.pop("version")
|
||||
'3.7'
|
||||
>>> dict
|
||||
{'language': 'python'}
|
||||
```
|
||||
|
||||
##### Supprimer la dernière entrée (popitem):
|
||||
|
||||
```python
|
||||
>>> dict["version"] = "3.7"
|
||||
>>> dict["type"] = "interpreté"
|
||||
>>> dict
|
||||
{'language': 'python', 'version': '3.7', 'type': 'interprete'}
|
||||
>>> dict.popitem()
|
||||
('type', 'interprete')
|
||||
>>> dict
|
||||
{'language': 'python', 'version': '3.7'}
|
||||
```
|
||||
|
||||
##### Supprimer un dictionnaire (del):
|
||||
|
||||
```python
|
||||
>>> un_dict = {'language': 'python', 'version': '3.7'}
|
||||
>>> del un_dict
|
||||
>>> un_dict
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
NameError: name 'un_dict' is not defined
|
||||
```
|
||||
|
||||
##### Vider un dictionnaire (clear):
|
||||
|
||||
```python
|
||||
>>> un_dict = {'language': 'python', 'version': '3.7'}
|
||||
>>> un_dict.clear()
|
||||
>>> un_dict
|
||||
{}
|
||||
```
|
||||
|
||||
##### Récupérer les clés par une boucle (keys):
|
||||
|
||||
```python
|
||||
>>> for cle in dict.keys():
|
||||
... print(cle)
|
||||
...
|
||||
language
|
||||
version
|
||||
|
||||
>>> for cle in dict:
|
||||
... print(cle)
|
||||
...
|
||||
language
|
||||
version
|
||||
```
|
||||
|
||||
##### Récupérer les valeurs par une boucle (values):
|
||||
|
||||
```python
|
||||
>>> for valeur in dict.values():
|
||||
... print(valeur)
|
||||
...
|
||||
python
|
||||
3.7
|
||||
|
||||
>>> for val in dict:
|
||||
... print(dict[val])
|
||||
...
|
||||
python
|
||||
3.7
|
||||
```
|
||||
|
||||
##### Récupérer les clés et les valeurs par une boucle (items):
|
||||
|
||||
```python
|
||||
>>> for cle, valeur in dict.items():
|
||||
... print(cle, valeur)
|
||||
...
|
||||
language python
|
||||
version 3.7
|
||||
```
|
||||
|
||||
Vérifier si une clé existe dans un dictionnaire:
|
||||
|
||||
```python
|
||||
>>> dict = {'language': 'python', 'version': '3.7'}
|
||||
>>> if "language" in dict:
|
||||
... print("'language' est dans dict")
|
||||
...
|
||||
'language' est dans dict
|
||||
```
|
||||
|
||||
Longueur d'un dictionnaire:
|
||||
|
||||
```python
|
||||
>>> dict = {'language': 'python', 'version': '3.7'}
|
||||
>>> print(len(dict))
|
||||
2
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Copier un dictionnaire (copy):
|
||||
|
||||
```python
|
||||
>>> autre_dict = dict.copy()
|
||||
>>> autre_dict
|
||||
{'language': 'python', 'version': '3.7'}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#### Méthodes:
|
||||
|
||||
| Méthode | Description |
|
||||
| ------------ | ----------- |
|
||||
| clear() | |
|
||||
| copy() | |
|
||||
| fromkeys() | |
|
||||
| get() | |
|
||||
| items() | |
|
||||
| keys() | |
|
||||
| pop() | |
|
||||
| popitem() | |
|
||||
| setdefault() | |
|
||||
| update() | |
|
||||
| values() | |
|
||||
|
||||
33
docs/Programmation/Python/fabric-ssh.md
Normal file
33
docs/Programmation/Python/fabric-ssh.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# Fabric SSH Python
|
||||
|
||||
|
||||
|
||||
Installer fabric et paramiko:
|
||||
|
||||
```bash
|
||||
$ pip install fabric
|
||||
$ pip install paramiko
|
||||
|
||||
# CryptographyDeprecationWarning
|
||||
$ pip install cryptography==2.5
|
||||
```
|
||||
|
||||
|
||||
|
||||
`fabfile.py`
|
||||
|
||||
```python
|
||||
from fabric import Connection
|
||||
c = Connection(host='192.168.1.7', user='bruno', port=42666)
|
||||
|
||||
result = c.run('uname -s')
|
||||
|
||||
result = c.put(local='/Users/bruno/test.csv', remote='/homes/bruno')
|
||||
|
||||
result = c.get(remote='/homes/bruno/httpd-vhost.conf', local='/Users/bruno/Downloads/')
|
||||
result = c.get(remote='/homes/bruno/httpd-vhost.conf')
|
||||
|
||||
# erreur avec '/homes/bruno/hello.py'
|
||||
result = c.run('python hello.py')
|
||||
```
|
||||
|
||||
208
docs/Programmation/Python/fichiers.md
Normal file
208
docs/Programmation/Python/fichiers.md
Normal file
@@ -0,0 +1,208 @@
|
||||
# Fichiers
|
||||
|
||||
|
||||
|
||||
#### Fonction open:
|
||||
|
||||
##### Ouvrir un fichier:
|
||||
|
||||
```python
|
||||
fichier = open("test.py","r")
|
||||
print(fichier)
|
||||
fichier.close()
|
||||
|
||||
>>> <_io.TextIOWrapper name='test.py' mode='r' encoding='UTF-8'>
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Ouvrir et afficher un fichier:
|
||||
|
||||
```python
|
||||
fichier = open("test.py","r")
|
||||
print(fichier.read())
|
||||
fichier.close()
|
||||
```
|
||||
|
||||
Autre syntaxe:
|
||||
|
||||
```python
|
||||
with open("test.py","r") as fichier:
|
||||
print(fichier.read())
|
||||
```
|
||||
|
||||
Parcourrir un fichier ligne par ligne:
|
||||
|
||||
```python
|
||||
>>> fichier = open("serve.py","r")
|
||||
>>> for x in fichier:
|
||||
... print(x)
|
||||
...
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Ecrire dans un fichier (à la suite, sur une nouvelle ligne):
|
||||
|
||||
```python
|
||||
fichier = open("test.py","a")
|
||||
fichier.write("\n\n\"\"\" Commentaire \"\"\"")
|
||||
fichier.close()
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Type d'ouverture:
|
||||
|
||||
```python
|
||||
r, pour une ouverture en lecture (READ).
|
||||
w, pour une ouverture en écriture (WRITE), à chaque ouverture le contenu du fichier est écrasé. Si le fichier n'existe pas python le crée.
|
||||
a, pour une ouverture en mode ajout à la fin du fichier (APPEND). Si le fichier n'existe pas python le crée.
|
||||
b, pour une ouverture en mode binaire.
|
||||
t, pour une ouverture en mode texte.
|
||||
x, crée un nouveau fichier et l'ouvre pour écriture
|
||||
```
|
||||
|
||||
##### Test si un fichier existe:
|
||||
|
||||
```python
|
||||
import os
|
||||
if os.path.exists("serve.py"):
|
||||
print("Le fichier existe")
|
||||
else:
|
||||
print("Le fichier n'existe pas")
|
||||
```
|
||||
|
||||
##### Supprimer un fichier:
|
||||
|
||||
```python
|
||||
import os
|
||||
if os.path.exists("zz.py"):
|
||||
os.remove("zz.py")
|
||||
```
|
||||
|
||||
##### Supprimer un dossier:
|
||||
|
||||
```python
|
||||
import os
|
||||
if os.path.exists("empty_folder"):
|
||||
os.rmdir("empty_folder")
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Chemins
|
||||
|
||||
##### Méthodes:
|
||||
|
||||
```
|
||||
>>> help(os.path)
|
||||
|
||||
abspath(path) → Retourne un chemin absolu
|
||||
basename(p) → Retourne le dernier élément d'un chemin
|
||||
commonprefix(list) → Retourne le chemin commun le plus long d'une liste de chemins
|
||||
dirname(p) → Retourne le dossier parent de l'élément
|
||||
exists(path) → Test si un chemin existe
|
||||
getaTime(filename) → Retourne la date du dernier accès au fichier [os.stat()]
|
||||
getctime(filename) → Retourne la date du dernier changement de metadonnées du fichier
|
||||
getmTime(filename) → Retourne la date de la dernière modification du fichier
|
||||
getsize(filename) → Retourne la tailkle d'un fichier (en octets)
|
||||
isabs(s) → Test si un chemin est absolu
|
||||
isdir(s) → Test si le chemin est un dossier
|
||||
isfile(path) → Test si le chemin est un fichier régulier
|
||||
islink(path) → Test si le chemin est un lien symbolique
|
||||
ismount(path) → Test si le chemin est un point de montage
|
||||
join(path, s) → Ajoute un élément au chemin passé en paramètre
|
||||
normcase(s) → Normalise la casse d'un chemin
|
||||
normpath(path) → Normalise le chemin, élimine les doubles barres obliques, etc.
|
||||
realpath(filename) → Retourne le chemin canonique du nom de fichier spécifié (élimine les liens symboliques)
|
||||
samefile(f1, f2) → Test si deux chemins font référence au même fichier réel
|
||||
sameopenfile(f1, f2) → Test si deux objets de fichiers ouverts font référence au même fichier
|
||||
split(p) → Fractionne un chemin d'accès. Retourne un tuple
|
||||
```
|
||||
|
||||
##### Exemples:
|
||||
|
||||
```python
|
||||
>>> import os.path
|
||||
>>> help(os.path)
|
||||
|
||||
>>> path = "/Users/bruno/PycharmProjects/webserver/index.py"
|
||||
|
||||
>>> os.path.dirname(path)
|
||||
'/Users/bruno/PycharmProjects/webserver'
|
||||
>>> os.path.basename(path)
|
||||
'index.py'
|
||||
>>> os.path.split(path)
|
||||
('/Users/bruno/PycharmProjects/webserver', 'index.py')
|
||||
>>> os.path.abspath(".")
|
||||
'/Users/bruno'
|
||||
```
|
||||
|
||||
```python
|
||||
>>> os.listdir(os.path.dirname(path))
|
||||
['functions.py', 'server.py', 'index.py', 'serve.py', '__pycache__', 'test.py', 'open.py', '.idea']
|
||||
```
|
||||
|
||||
```python
|
||||
# lister récursivement tous les fichiers
|
||||
|
||||
>>> import os
|
||||
>>> folder = '/Users/bruno/PycharmProjects'
|
||||
>>> for path, dirs, files in os.walk(folder):
|
||||
... for filename in files:
|
||||
... print(filename)
|
||||
...
|
||||
.DS_Store
|
||||
pyvenv.cfg
|
||||
pip3.7
|
||||
python3
|
||||
easy_install
|
||||
python
|
||||
.../...
|
||||
```
|
||||
|
||||
##### Connaître le répertoire courante:
|
||||
|
||||
```python
|
||||
>>> import os
|
||||
>>> os.getcwd()
|
||||
'/Users/bruno/PycharmProjects/webserver'
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Rechercher des éléments par motif
|
||||
|
||||
```
|
||||
* → n'importe quel séquence de caractères
|
||||
? → n'importe quel caractère
|
||||
[] → n'importe quel caractère listé entre les crochets
|
||||
```
|
||||
|
||||
```python
|
||||
>>> import glob
|
||||
|
||||
# Methodes:
|
||||
glob.glob(motif) → Liste les dossiers et les fichiers correspondants au motif
|
||||
glob.iglob(motif) → Idem que glob mais retourne un itérateur
|
||||
|
||||
# Recherche des fichiers python:
|
||||
>>> glob.glob("/Users/bruno/PycharmProjects/webserver/*.py")
|
||||
['/Users/bruno/PycharmProjects/webserver/functions.py', '/Users/bruno/PycharmProjects/webserver/server.py', '/Users/bruno/PycharmProjects/webserver/index.py', '/Users/bruno/PycharmProjects/webserver/serve.py', '/Users/bruno/PycharmProjects/webserver/test.py', '/Users/bruno/PycharmProjects/webserver/open.py']
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Manipuler les éléments
|
||||
|
||||
```python
|
||||
os.makedirs(path) → Créer récursivement tous les dossiers d'un path si ceux-ci n'existent pas
|
||||
os.mkdir(path) → Créer le dernier dossier d'un path. Si un des dossiers n'existe pas une erreur est retournée
|
||||
os.remove(path) → Supprime le fichier / dossier indiqué
|
||||
os.rename(old, new) → Renomme le fichier / dossier indiqué
|
||||
```
|
||||
|
||||
|
||||
|
||||
414
docs/Programmation/Python/fonctions.md
Normal file
414
docs/Programmation/Python/fonctions.md
Normal file
@@ -0,0 +1,414 @@
|
||||
# Fonctions
|
||||
|
||||
|
||||
|
||||
#### Fonctions natives:
|
||||
|
||||
##### abs(x)
|
||||
|
||||
```python
|
||||
# -retourne la valeur absolue
|
||||
>>> abs(-3)
|
||||
3
|
||||
```
|
||||
|
||||
##### all(iterable)
|
||||
|
||||
```python
|
||||
# -retourne True si tous les éléments d'un élément itérable sont True
|
||||
>>> liste = [True, True, True, 1]
|
||||
>>> all(liste)
|
||||
True
|
||||
```
|
||||
|
||||
##### any(iterable)
|
||||
|
||||
```python
|
||||
# -retourne True si au moins un élément d'un élément itérable est True
|
||||
>>> liste = [True, False, True, 1]
|
||||
>>> any(liste)
|
||||
True
|
||||
|
||||
```
|
||||
|
||||
##### bin(x)
|
||||
|
||||
```python
|
||||
# -convertit un entier en chaine de caractères binaires
|
||||
>>> bin(132)
|
||||
'0b10000100'
|
||||
|
||||
```
|
||||
|
||||
##### bool()
|
||||
|
||||
```python
|
||||
# -retourne la valeur boléenne
|
||||
>>> bool(12)
|
||||
True
|
||||
>>> bool(0)
|
||||
False
|
||||
```
|
||||
|
||||
##### callable
|
||||
|
||||
```python
|
||||
# -détermine si un objet est callable (exécutable ou appelable)
|
||||
# -fonctions (user ou builtin), methodes
|
||||
>>> callable("A")
|
||||
False
|
||||
>>> callable(int)
|
||||
True
|
||||
|
||||
```
|
||||
|
||||
##### chr(n)
|
||||
|
||||
```python
|
||||
# -retourne la caractère qui correspond à l'unicode n
|
||||
>>> chr(97)
|
||||
'a'
|
||||
```
|
||||
|
||||
##### delattr()
|
||||
|
||||
```python
|
||||
# -efface un attribut d'un objet
|
||||
|
||||
class Person:
|
||||
name = "John"
|
||||
age = 36
|
||||
country = "Norway"
|
||||
|
||||
delattr(Person, 'age')
|
||||
```
|
||||
|
||||
##### eval(expression)
|
||||
|
||||
```python
|
||||
# -
|
||||
>>> v =101
|
||||
>>> eval('v+1')
|
||||
102
|
||||
|
||||
```
|
||||
|
||||
##### format(val, format)
|
||||
|
||||
```python
|
||||
# -formatte une valeur selon le format. spécifié
|
||||
>>> x = format(5, 'b') # binaire
|
||||
>>> x
|
||||
'101'
|
||||
>>> x = format(44, 'x') # hexa
|
||||
>>> x
|
||||
'2c'
|
||||
```
|
||||
|
||||
##### getattr(objet, attribut)
|
||||
|
||||
```python
|
||||
# -retourne la valeur de l'attribut de l'objet spécifié
|
||||
class Person:
|
||||
name = "John"
|
||||
age = 36
|
||||
country = "Norway"
|
||||
|
||||
x = getattr(Person, 'age')
|
||||
36
|
||||
```
|
||||
|
||||
##### hasattr(objet, attribut)
|
||||
|
||||
```python
|
||||
# -retourne True si l'objet spécifié à l'attribut
|
||||
class Person:
|
||||
name = "John"
|
||||
age = 36
|
||||
country = "Norway"
|
||||
|
||||
x = hasattr(Person, 'age')
|
||||
True
|
||||
```
|
||||
|
||||
##### help(element)
|
||||
|
||||
```python
|
||||
# -retourne l'aide sur l'élément
|
||||
>>> help(tuple)
|
||||
|
||||
Help on class tuple in module builtins:
|
||||
|
||||
class tuple(object)
|
||||
| tuple(iterable=(), /)
|
||||
|
|
||||
| Built-in immutable sequence.
|
||||
|
||||
|
||||
```
|
||||
|
||||
##### hex()
|
||||
|
||||
```python
|
||||
# -convertit un nombre en hexa`
|
||||
>>> hex(15)
|
||||
'0xf'
|
||||
|
||||
```
|
||||
|
||||
##### locals()
|
||||
|
||||
```python
|
||||
# -retourne un dictionnaire avec des variables en cours
|
||||
|
||||
|
||||
```
|
||||
|
||||
##### map(function)
|
||||
|
||||
```python
|
||||
# -exécute une fonction sur chaque item d'un élément itérable
|
||||
|
||||
|
||||
```
|
||||
|
||||
##### max() / min()
|
||||
|
||||
```python
|
||||
# -retourne la valeur maxi ou mini
|
||||
|
||||
>>> min([1,3,6,99,125,-3])
|
||||
-3
|
||||
>>> max([1,3,6,99,125,-3])
|
||||
125
|
||||
|
||||
```
|
||||
|
||||
##### next(iterable)
|
||||
|
||||
```python
|
||||
# -retourne l'item suivant d'un itérable
|
||||
>>> mylist = iter(["apple", "banana", "cherry"])
|
||||
>>> x = next(mylist)
|
||||
>>> x
|
||||
'apple'
|
||||
>>> x = next(mylist)
|
||||
>>> x
|
||||
'banana'
|
||||
```
|
||||
|
||||
##### ord(caractère)
|
||||
|
||||
```python
|
||||
# -retourne le code unicode du caractère
|
||||
>>> x = ord("€")
|
||||
>>> x
|
||||
8364
|
||||
```
|
||||
|
||||
##### pow(x, y, z)
|
||||
|
||||
```python
|
||||
# -retourne x puissance y (modulo z)
|
||||
>>> pow(2,4)
|
||||
16
|
||||
```
|
||||
|
||||
##### print(object(s) separator=separator, end=end, file=file, flush=flush)
|
||||
|
||||
```python
|
||||
# -affiche le message à l'écran ou sur une autre sortie
|
||||
# -par défaut, end='\'
|
||||
>>> print("Hello", "how are you?", sep=" --- ")
|
||||
Hello --- how are you?
|
||||
|
||||
fichier = open("test.py","r")
|
||||
print(fichier.read())
|
||||
fichier.close()
|
||||
```
|
||||
|
||||
##### randint()
|
||||
|
||||
```python
|
||||
# -retourne un entier aléatoire
|
||||
|
||||
>>> import random
|
||||
>>> random.randint(1,100)
|
||||
76
|
||||
|
||||
```
|
||||
|
||||
##### random()
|
||||
|
||||
```python
|
||||
# -retourne une valeur aléatoire
|
||||
|
||||
>>> import random
|
||||
>>> random.random()
|
||||
0.893485376651602
|
||||
|
||||
```
|
||||
|
||||
##### range(x)
|
||||
|
||||
```python
|
||||
# -crée une séquence de nombre de 0 à x (exclu)
|
||||
x = range(4) # de 0 à 3
|
||||
for n in x:
|
||||
print(n)
|
||||
0
|
||||
1
|
||||
2
|
||||
3
|
||||
|
||||
x = range(3, 6) # de 3 à 5
|
||||
for n in x:
|
||||
print(n)
|
||||
3
|
||||
4
|
||||
5
|
||||
|
||||
x = range(0,6,2) # de 0 à 5 et un pas de 2
|
||||
for n in x:
|
||||
print(n)
|
||||
0
|
||||
2
|
||||
4
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### reverse()
|
||||
|
||||
```python
|
||||
# -inverse l'ordre d'une liste
|
||||
|
||||
>>> x = [1,2,3]
|
||||
>>> x.reverse()
|
||||
>>> x
|
||||
[3, 2, 1]
|
||||
|
||||
```
|
||||
|
||||
##### reversed()
|
||||
|
||||
```python
|
||||
# -retourne un itérateur inversé
|
||||
|
||||
>>> list(reversed([1,2,3,4]))
|
||||
[4, 3, 2, 1]
|
||||
|
||||
```
|
||||
|
||||
##### round(number)
|
||||
|
||||
```python
|
||||
# -retourne l'arrondi d'un nombre
|
||||
|
||||
>>> round(-1.2)
|
||||
-1
|
||||
>>> round(-1.2563679)
|
||||
-1
|
||||
|
||||
```
|
||||
|
||||
##### set(iterable)
|
||||
|
||||
```python
|
||||
# -crée un objet set
|
||||
# -un set est une collection non ordonnée et non indexé
|
||||
|
||||
x = set(('apple', 'banana', 'cherry'))
|
||||
>>> x
|
||||
{'apple', 'cherry', 'banana'}
|
||||
```
|
||||
|
||||
##### slice(start, end, step)
|
||||
|
||||
```python
|
||||
# -retourne un objet slice
|
||||
>>> a = ("a", "b", "c", "d", "e", "f", "g", "h")
|
||||
|
||||
>>> x = slice(2)
|
||||
>>> print(a[x])
|
||||
('a', 'b')
|
||||
|
||||
>>> x = slice(3, 5)
|
||||
>>> print(a[x])
|
||||
('d', 'e')
|
||||
|
||||
>>> x = slice(0, 8, 3)
|
||||
>>> print(a[x])
|
||||
('a', 'd', 'g')
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### shuffle()
|
||||
|
||||
```python
|
||||
# -mélange aléatoirement une liste
|
||||
|
||||
>>> import random
|
||||
>>> x = [1,2,3,4,5]
|
||||
>>> random.shuffle(x)
|
||||
>>> x
|
||||
[2, 5, 4, 1, 3]
|
||||
|
||||
```
|
||||
|
||||
##### list.sort()
|
||||
|
||||
```python
|
||||
# -permet de trier une liste
|
||||
|
||||
>>> l = [67,34,89,12,70,345,2,-56]
|
||||
>>> l.sort()
|
||||
>>> l
|
||||
[-56, 2, 12, 34, 67, 70, 89, 345]
|
||||
|
||||
```
|
||||
|
||||
##### sorted(iterable)
|
||||
|
||||
```python
|
||||
# -tri un élément itérable
|
||||
|
||||
>>> sorted([3,2,12,1])
|
||||
[1, 2, 3, 12]
|
||||
|
||||
```
|
||||
|
||||
##### sum(iterable)
|
||||
|
||||
```python
|
||||
# -retourne la somme des valeurs d'un élément itérable
|
||||
|
||||
>>> sum([12,24,36])
|
||||
72
|
||||
```
|
||||
|
||||
##### upper()
|
||||
|
||||
```python
|
||||
# -met en majuscule la chaine de caractères
|
||||
|
||||
>>> "Python".upper()
|
||||
'PYTHON'
|
||||
```
|
||||
|
||||
##### zip(*iterables)
|
||||
|
||||
```python
|
||||
# -permet de regrouper sous la forme d'un tuple les items de listes.
|
||||
# - https://stackoverflow.com/questions/31683959/the-zip-function-in-python-3
|
||||
|
||||
>>> a = ["sharon", "sophie", "halle"]
|
||||
>>> b = ["stone", "marceau", "berry"]
|
||||
>>> zip(a,b)
|
||||
<zip object at 0x10e1009c8>
|
||||
>>> list(zip(a,b))
|
||||
[('sharon', 'stone'), ('sophie', 'marceau'), ('halle', 'berry')]
|
||||
```
|
||||
|
||||
292
docs/Programmation/Python/liste.md
Normal file
292
docs/Programmation/Python/liste.md
Normal file
@@ -0,0 +1,292 @@
|
||||
# Listes
|
||||
|
||||
|
||||
|
||||
Une liste est une collection **ordonnée** et **modifiable**. C'est ce qui se rapproche le plus des tableaux (array).
|
||||
|
||||
|
||||
|
||||
##### Créer une liste:
|
||||
|
||||
```python
|
||||
liste = []
|
||||
```
|
||||
|
||||
```python
|
||||
# Constructor list()
|
||||
liste = list(("alpha", "banana", "cherry"))
|
||||
```
|
||||
|
||||
##### Ajouter une valeur (append):
|
||||
|
||||
```python
|
||||
>>> liste = [1,2,3]
|
||||
>>> liste
|
||||
[1, 2, 3]
|
||||
|
||||
>>>> liste.append(4)
|
||||
>>> liste
|
||||
[1, 2, 3, 4]
|
||||
|
||||
>>> liste.append("Bonjour")
|
||||
>>> liste
|
||||
[1, 2, 3, 4, 'Bonjour']
|
||||
```
|
||||
|
||||
##### Afficher un item:
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Bonjour']
|
||||
>>> liste[0]
|
||||
1
|
||||
>>> liste[4]
|
||||
'Bonjour'
|
||||
```
|
||||
|
||||
##### Modifier un item:
|
||||
|
||||
```python
|
||||
>>> liste[4] = "Hello"
|
||||
>>> liste
|
||||
[1, 2, 3, 4, 'Hello']
|
||||
```
|
||||
|
||||
##### Supprimer un item (remove):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Hello']
|
||||
>>> liste.remove(2)
|
||||
>>> liste
|
||||
[1, 3, 4, 'Hello']
|
||||
```
|
||||
|
||||
##### Supprimer un item (pop):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Hello']
|
||||
>>> liste.pop() # supprimer l'index spécifié ou le dernier
|
||||
>>> liste
|
||||
[1, 2, 3, 4]
|
||||
```
|
||||
|
||||
##### Supprimer un item (del):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Hello']
|
||||
>>> del liste[1]
|
||||
>>> liste
|
||||
[1, 3, 4, 'Hello']
|
||||
```
|
||||
|
||||
##### Supprimer la liste (del):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Hello']
|
||||
>>> del liste
|
||||
>>> liste
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
NameError: name 'liste' is not defined
|
||||
```
|
||||
|
||||
##### Vider la liste (clear):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Hello']
|
||||
>>> liste.clear()
|
||||
>>> liste
|
||||
[]
|
||||
```
|
||||
|
||||
##### Inverser les items (reverse):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 3, 4, 'Hello']
|
||||
>>> liste.reverse()
|
||||
>>> liste
|
||||
['Hello', 4, 3, 1]
|
||||
```
|
||||
|
||||
##### Nb d'items (len):
|
||||
|
||||
```python
|
||||
>>> liste = ['Hello', 4, 3, 1]
|
||||
>>> len(liste)
|
||||
4
|
||||
```
|
||||
|
||||
##### Nb d'occurences d'une valeur (count):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Bonjour', 1, 1]
|
||||
>>> liste
|
||||
[1, 2, 3, 4, 'Bonjour', 1, 1]
|
||||
>>> liste.index(1)
|
||||
0
|
||||
>>> liste.count(1)
|
||||
3
|
||||
```
|
||||
|
||||
##### Index d'une valeur (index):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Bonjour', 1, 1]
|
||||
>>> liste.index("Bonjour")
|
||||
4
|
||||
```
|
||||
|
||||
##### Manipuler une liste:
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Bonjour', 1, 1]
|
||||
>>> liste
|
||||
[1, 2, 3, 4, 'Bonjour', 1, 1]
|
||||
|
||||
# Dernière occurence
|
||||
>>> liste[-1]
|
||||
1
|
||||
|
||||
# 3e occurence en partant de la fin
|
||||
>>> liste[-3]
|
||||
'Bonjour'
|
||||
|
||||
# 2 premières occurences
|
||||
>>> liste[:2]
|
||||
[1, 2]
|
||||
|
||||
# 3 dernières occurences
|
||||
>>> liste[-3:]
|
||||
['Bonjour', 1, 1]
|
||||
|
||||
# vider la liste
|
||||
>>> liste[:] = []
|
||||
>>>
|
||||
```
|
||||
|
||||
##### Boucle:
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Bonjour', 1, 1]
|
||||
>>> for i in liste:
|
||||
... print (i)
|
||||
...
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
Bonjour
|
||||
1
|
||||
1
|
||||
|
||||
|
||||
```
|
||||
|
||||
##### Boucle (avec l'index):
|
||||
|
||||
```python
|
||||
>>> liste = [1, 2, 3, 4, 'Bonjour', 1, 1]
|
||||
>>> for i in enumerate(liste):
|
||||
... print (i)
|
||||
...
|
||||
(0, 1)
|
||||
(1, 2)
|
||||
(2, 3)
|
||||
(3, 4)
|
||||
(4, 'Bonjour')
|
||||
(5, 1)
|
||||
(6, 1)
|
||||
# Les valeurs retournées par la boucle sont des tuples.
|
||||
```
|
||||
|
||||
##### Copier une liste:
|
||||
|
||||
```python
|
||||
>>> x = [1, 2, 3]
|
||||
>>> y = x[:]
|
||||
>>> y[0] = 0
|
||||
>>> x
|
||||
[1, 2, 3]
|
||||
>>> y
|
||||
[0, 2, 3]
|
||||
```
|
||||
|
||||
##### Transformer une string en liste (split):
|
||||
|
||||
```python
|
||||
>>> string = "Language:Version:OS"
|
||||
>>> z = string.split(":")
|
||||
>>> z
|
||||
['Language', 'Version', 'OS']
|
||||
```
|
||||
|
||||
##### Transformer une liste en string (join):
|
||||
|
||||
```python
|
||||
>>> liste = ['semis','date','lune']
|
||||
>>> ";".join(liste)
|
||||
'semis;date;lune'
|
||||
```
|
||||
|
||||
##### Trouver un item dans une liste (in):
|
||||
|
||||
```python
|
||||
>>> liste = ['semis','date','lune']
|
||||
>>> 'lune' in liste
|
||||
True
|
||||
>>> 'meteo' in liste
|
||||
False
|
||||
```
|
||||
|
||||
##### Range:
|
||||
|
||||
```python
|
||||
>>> range(0, 10)
|
||||
```
|
||||
|
||||
##### Concaténer 2 listes (extend, +):
|
||||
|
||||
```python
|
||||
>>> a = [1, 2, 3]
|
||||
>>> b = [4, 5 ,6]
|
||||
>>> a.extend(b)
|
||||
>>> print(a)
|
||||
[1, 2, 3, 4, 5, 6]
|
||||
>>> c = a + b
|
||||
>>> print(c)
|
||||
[1, 2, 3, 4, 5, 6, 4, 5, 6]
|
||||
```
|
||||
|
||||
##### Multiplier une liste (utile pour l'initialiser):
|
||||
|
||||
```python
|
||||
>>> a = [0] * 4
|
||||
>>> print(a)
|
||||
[0, 0, 0, 0]
|
||||
```
|
||||
|
||||
##### Vérifier si un item est présent dans une liste:
|
||||
|
||||
```python
|
||||
thislist = ["alpha", "beta", "gamma"]
|
||||
if "alpha" in thislist:
|
||||
print("Oui, 'alpha' est dans la liste")
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Méthodes:
|
||||
|
||||
| Méthode | Description |
|
||||
| --------- | ----------- |
|
||||
| append() | |
|
||||
| clear() | |
|
||||
| copy() | |
|
||||
| count() | |
|
||||
| extend() | |
|
||||
| index() | |
|
||||
| insert() | |
|
||||
| pop() | |
|
||||
| remove() | |
|
||||
| reverse() | |
|
||||
| sort() | |
|
||||
|
||||
85
docs/Programmation/Python/regex.md
Normal file
85
docs/Programmation/Python/regex.md
Normal file
@@ -0,0 +1,85 @@
|
||||
# regex
|
||||
|
||||
|
||||
|
||||
```python
|
||||
. Le point correspond à n'importe quel caractère.
|
||||
^ Indique un commencement de segment mais signifie aussi "contraire de"
|
||||
$ Fin de segment
|
||||
[xy] Une liste de segment possibble. Exemple [abc] équivaut à : a, b ou c
|
||||
(x|y) Indique un choix multiple type (ps|ump) équivaut à "ps" OU "UMP"
|
||||
\d le segment est composé uniquement de chiffre, ce qui équivaut à [0-9].
|
||||
\D le segment n'est pas composé de chiffre, ce qui équivaut à [^0-9].
|
||||
\s Un espace, ce qui équivaut à [ \t\n\r\f\v].
|
||||
\S Pas d'espace, ce qui équivaut à [^ \t\n\r\f\v].
|
||||
\w Présence alphanumérique, ce qui équivaut à [a-zA-Z0-9_].
|
||||
\W Pas de présence alphanumérique [^a-zA-Z0-9_].
|
||||
\ Est un caractère d'échappement
|
||||
\t\n\r Tab, newline, retour
|
||||
```
|
||||
|
||||
##### Nombre d'occurrences:
|
||||
|
||||
```python
|
||||
A{2} : on attend à ce que la lettre A (en majuscule) se répète 2 fois consécutives.
|
||||
BA{1,9} : on attend à ce que le segment BA se répète de 1 à 9 fois consécutives.
|
||||
BRA{,10} : on attend à ce que le segment BRA ne soit pas présent du tout ou présent jusqu'à 10 fois consécutives.
|
||||
VO{1,} : on attend à ce que le segment VO soit présent au mois une fois.
|
||||
```
|
||||
|
||||
|
||||
|
||||
| Symbole | Nb caractères attendus | Exemples |
|
||||
| ------- | ---------------------- | --------- |
|
||||
| ? | 0 ou 1 | Pyt(.)?on |
|
||||
| + | 1 ou plus | Pyt(.)+on |
|
||||
| * | 0, 1 ou plus | Pyt(.)*on |
|
||||
|
||||
|
||||
|
||||
##### Fonction match():
|
||||
|
||||
```python
|
||||
re.match(pattern, string, flags = 0)
|
||||
```
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
>>> x = re.match(r"Py(.)?hon", "Python")
|
||||
>>> x
|
||||
<re.Match object; span=(0, 6), match='Python'>
|
||||
|
||||
>>> x = re.match(r"Py(.)?hon", "Pithon")
|
||||
>>> x
|
||||
```
|
||||
|
||||
|
||||
|
||||
Fonction search():
|
||||
|
||||
```python
|
||||
re.search(pattern, string, flags = 0)
|
||||
```
|
||||
|
||||
|
||||
|
||||
Options flags:
|
||||
|
||||
| | Description |
|
||||
| ---- | ----------- |
|
||||
| 1 | re.I |
|
||||
| 2 | re.L |
|
||||
| 3 | re.M |
|
||||
| 4 | re.S |
|
||||
| 5 | re.U |
|
||||
| 6 | re.X |
|
||||
|
||||
|
||||
|
||||
Fonction sub():
|
||||
|
||||
```python
|
||||
re.sub(pattern, repl, string, max=0)
|
||||
```
|
||||
|
||||
131
docs/Programmation/Python/set.md
Normal file
131
docs/Programmation/Python/set.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# Set
|
||||
|
||||
|
||||
|
||||
Une liste est une collection **non ordonnée** et **non indexée**. On ne peut pas modifier un item, mais on peut en ajouter.
|
||||
|
||||
|
||||
|
||||
##### Créer un set:
|
||||
|
||||
```python
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set
|
||||
{'alpha', 'beta', 'gamma'}
|
||||
```
|
||||
|
||||
```python
|
||||
# Constructor set()
|
||||
>>> un_set = set(("alpha", "beta", "gamma"))
|
||||
>>> un_set
|
||||
{'gamma', 'alpha', 'beta'}
|
||||
```
|
||||
|
||||
##### Ajouter un item:
|
||||
|
||||
```python
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set.add("delta")
|
||||
>>> un_set
|
||||
{'gamma', 'alpha', 'beta', 'delta'}
|
||||
```
|
||||
|
||||
##### Ajouter plusieurs items:
|
||||
|
||||
```python
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set.update(["delta","zeta","epsilon"])
|
||||
>>> un_set
|
||||
{'zeta', 'alpha', 'beta', 'delta', 'gamma', 'epsilon'}
|
||||
```
|
||||
|
||||
##### Longueur d'un set:
|
||||
|
||||
```python
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> print(len(un_set))
|
||||
3
|
||||
```
|
||||
|
||||
##### Supprimer un item (remove):
|
||||
|
||||
```python
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set.remove("beta")
|
||||
>>> un_set
|
||||
{'gamma', 'alpha'}
|
||||
```
|
||||
|
||||
##### Supprimer un item (discard):
|
||||
|
||||
```python
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set.discard("beta")
|
||||
>>> un_set
|
||||
{'gamma', 'alpha'}
|
||||
```
|
||||
|
||||
##### Vider un set:
|
||||
|
||||
```python
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set.clear()
|
||||
>>> un_set
|
||||
set()
|
||||
```
|
||||
|
||||
##### Supprimer un set:
|
||||
|
||||
```python
|
||||
>>> del un_set
|
||||
>>> un_set
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
NameError: name 'un_set' is not defined
|
||||
```
|
||||
|
||||
##### Boucle:
|
||||
|
||||
```python
|
||||
un_set = {"alpha", "beta", "gamma"}
|
||||
for x in un_set:
|
||||
print(x)
|
||||
|
||||
alpha
|
||||
beta
|
||||
gamma
|
||||
```
|
||||
|
||||
##### Test si un item est présent dans le set:
|
||||
|
||||
```python
|
||||
un_set = {"alpha", "beta", "gamma"}
|
||||
print("alpha" in un_set)
|
||||
|
||||
True
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Méthodes:
|
||||
|
||||
| Méthodes | Description |
|
||||
| ----------------------------- | ----------- |
|
||||
| add() | |
|
||||
| clear() | |
|
||||
| copy() | |
|
||||
| difference() | |
|
||||
| difference_update() | |
|
||||
| discard() | |
|
||||
| intersection() | |
|
||||
| intersection_update() | |
|
||||
| isdisjoint() | |
|
||||
| issubset() | |
|
||||
| issuperset() | |
|
||||
| pop() | |
|
||||
| remove() | |
|
||||
| symmetric_difference() | |
|
||||
| symmetric_difference_update() | |
|
||||
| union() | |
|
||||
| update() | |
|
||||
|
||||
210
docs/Programmation/Python/string.md
Normal file
210
docs/Programmation/Python/string.md
Normal file
@@ -0,0 +1,210 @@
|
||||
# Strings
|
||||
|
||||
|
||||
|
||||
##### str.count()
|
||||
|
||||
```python
|
||||
# -compte le nombre d'occurence de la chaine demandée
|
||||
>>> "programmation".count("m")
|
||||
2
|
||||
```
|
||||
|
||||
##### str.capitalize()
|
||||
|
||||
```python
|
||||
# -capitalise la chaine de caractère
|
||||
>>> "pYtHOn".capitalize()
|
||||
'Python'
|
||||
```
|
||||
|
||||
##### str.endswith(str)
|
||||
|
||||
```python
|
||||
# -teste si une chaine se termine par la chaine demandée (sensible à la casse)
|
||||
>>> a = "Python"
|
||||
>>> a.endswith("r")
|
||||
False
|
||||
>>> a.endswith("n")
|
||||
True
|
||||
```
|
||||
|
||||
##### str.find()
|
||||
|
||||
```python
|
||||
# -trouve la 1ere occurence de la chaine demandée
|
||||
>>> "capitalize".find("i")
|
||||
3
|
||||
```
|
||||
|
||||
##### str.isalnum()
|
||||
|
||||
```python
|
||||
# -retourne True si tous les caractères sont alphanumériques
|
||||
>>> "0xf".isalnum()
|
||||
True
|
||||
>>> "0xf_".isalnum()
|
||||
False
|
||||
|
||||
```
|
||||
|
||||
##### str.isalpha()
|
||||
|
||||
```python
|
||||
# -retourne True si tous les caractères sont des lettres
|
||||
>>> "0xf".isalpha()
|
||||
False
|
||||
>>> "abcdef".isalpha()
|
||||
True
|
||||
|
||||
```
|
||||
|
||||
##### str.isdigit()
|
||||
|
||||
```python
|
||||
# -retourne True si tous les caractères sont numériques
|
||||
>>> "1234".isalnum()
|
||||
True
|
||||
|
||||
```
|
||||
|
||||
##### str.islower()
|
||||
|
||||
```python
|
||||
# -retourne True si tous les caractères sont en minuscule
|
||||
>>> "python".islower()
|
||||
True
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### str.isspace()
|
||||
|
||||
```python
|
||||
# -retourne True si tous les caractères sont des espaces
|
||||
>>> "".isspace()
|
||||
False
|
||||
>>> " ".isspace()
|
||||
True
|
||||
>>> "un mot".isspace()
|
||||
False
|
||||
|
||||
```
|
||||
|
||||
##### str.istitle()
|
||||
|
||||
```python
|
||||
# -retourne True si la chaine à un format titre
|
||||
>>> "Python".istitle()
|
||||
True
|
||||
>>> "Python Est Un Language De Programmation".istitle()
|
||||
True
|
||||
|
||||
```
|
||||
|
||||
##### str.isupper()
|
||||
|
||||
```python
|
||||
# -retourne True si tous les caractères sont en majuscule
|
||||
>>> "PYTHON".isupper()
|
||||
True
|
||||
|
||||
```
|
||||
|
||||
##### str.join(liste)
|
||||
|
||||
```python
|
||||
# -transforme une liste en chaine
|
||||
|
||||
>>> ":".join(["language", "python"])
|
||||
'language:python'
|
||||
|
||||
```
|
||||
|
||||
##### len(s)
|
||||
|
||||
```python
|
||||
# -retourne le nb d'items d'un objet
|
||||
|
||||
>>> len(["language", "python"])
|
||||
2
|
||||
>>> len("Python")
|
||||
6
|
||||
|
||||
```
|
||||
|
||||
##### str.lower()
|
||||
|
||||
```python
|
||||
# -retourne la chaine en minuscule
|
||||
|
||||
>>> "PYTHON".lower()
|
||||
'python'
|
||||
|
||||
```
|
||||
|
||||
##### str.replace(str,str)
|
||||
|
||||
```python
|
||||
# -remplace un segement de chaine par un autre
|
||||
|
||||
>>> "Python est un language".replace("Python","Perl")
|
||||
'Perl est un language'
|
||||
|
||||
```
|
||||
|
||||
##### str.startswith()
|
||||
|
||||
```python
|
||||
# -retourne True si la chaine commence par le préfix indiqué (sensible à la casse)
|
||||
|
||||
>>> a = "Python"
|
||||
>>> a.startswith("P")
|
||||
True
|
||||
>>> a.startswith("y")
|
||||
False
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
##### str.split(séparateur)
|
||||
|
||||
```python
|
||||
# -transforme une chaine en liste
|
||||
|
||||
>>> "Language:Python".split(":")
|
||||
['Language', 'Python']
|
||||
|
||||
```
|
||||
|
||||
##### str.splitlines()
|
||||
|
||||
```python
|
||||
# -retourne une liste des lignes de la chaine
|
||||
|
||||
>>> "language\n\n\Python\n\n3.7".splitlines()
|
||||
['language', '', '\\Python', '', '3.7']
|
||||
>>> "language\nPython\n3.7".splitlines()
|
||||
['language', 'Python', '3.7']
|
||||
>>> "language\n\rPython\n\r3.7".splitlines()
|
||||
['language', '', 'Python', '', '3.7']
|
||||
>>> "language\r\nPython\r\n3.7".splitlines()
|
||||
['language', 'Python', '3.7']
|
||||
>>> "language\r\nPython\r\n\r\n3.7".splitlines()
|
||||
['language', 'Python', '', '3.7']
|
||||
>>> "language\r\nPython\r\n\r\n3.7".splitlines(True)
|
||||
['language\r\n', 'Python\r\n', '\r\n', '3.7']
|
||||
```
|
||||
|
||||
##### str.title()
|
||||
|
||||
```python
|
||||
# -transforme la chaine dans un format Titre
|
||||
|
||||
>>> "Ceci est un titre".title()
|
||||
'Ceci Est Un Titre'
|
||||
```
|
||||
|
||||
#####
|
||||
78
docs/Programmation/Python/tuple.md
Normal file
78
docs/Programmation/Python/tuple.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# Tuple
|
||||
|
||||
|
||||
|
||||
Un tuple est une liste qui ne peut être modifiée.
|
||||
|
||||
|
||||
|
||||
##### Créer un tuple
|
||||
|
||||
```python
|
||||
>>> un_tuple = ()
|
||||
```
|
||||
|
||||
##### Y ajouter des valeurs
|
||||
|
||||
```python
|
||||
>>> un_tuple = ("alpha","beta","gamma")
|
||||
>>> print(un_tuple)
|
||||
('alpha', 'beta', 'gamma')
|
||||
```
|
||||
|
||||
##### Si 1 seule valeur, ajouter une virgule, sinon c'est une chaine
|
||||
|
||||
```python
|
||||
>>> autre_tuple = ("un",)
|
||||
>>> type(autre_tuple)
|
||||
<class 'tuple'>
|
||||
>>> autre_tuple = ("un")
|
||||
>>> type(autre_tuple)
|
||||
<class 'str'>
|
||||
```
|
||||
|
||||
##### Afficher une valeur d'un tuple
|
||||
|
||||
```python
|
||||
>>> un_tuple[0]
|
||||
'alpha'
|
||||
```
|
||||
|
||||
##### Les tuples ne sont pas modifiables (ni modif, ni ajout, ni suppression)
|
||||
|
||||
```python
|
||||
>>> un_tuple[0] = "delta"
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: 'tuple' object does not support item assignment
|
||||
```
|
||||
|
||||
##### Test si un item existe:
|
||||
|
||||
```python
|
||||
>>> if "alpha" in un_tuple:
|
||||
... print("'alpha' est dans le tuple")
|
||||
...
|
||||
'alpha' est dans le tuple
|
||||
```
|
||||
|
||||
##### Boucle:
|
||||
|
||||
```python
|
||||
>>> for x in un_tuple:
|
||||
... print(x)
|
||||
...
|
||||
alpha
|
||||
beta
|
||||
gamma
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Méthodes:
|
||||
|
||||
| Méthode | Description |
|
||||
| ------- | ----------- |
|
||||
| count() | |
|
||||
| index() | |
|
||||
|
||||
Reference in New Issue
Block a user