teaching:progappchim:notions_fondamentales

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentes Révision précédente
Prochaine révision
Révision précédente
Prochaine révisionLes deux révisions suivantes
teaching:progappchim:notions_fondamentales [2021/01/11 12:01] – [Le type de données texte ou "string" :] villersdteaching:progappchim:notions_fondamentales [2021/01/25 11:57] – [Le type de données texte ou "string" :] villersd
Ligne 91: Ligne 91:
  
 //Cf.// [[http://www.courspython.com/boucles.html|cet autre cours]] avec des illustrations et des exemples de code exécutable sur le site [[http://www.pythontutor.com|pythontutor]]. //Cf.// [[http://www.courspython.com/boucles.html|cet autre cours]] avec des illustrations et des exemples de code exécutable sur le site [[http://www.pythontutor.com|pythontutor]].
 +
 +FIXME : ajouter d'autres possibilités telles que présentées dans [[https://medium.com/analytics-vidhya/looping-techniques-in-python-3bbf907b8dfa|Looping Techniques in Python - Let’s learn about looping techniques using functions like enumerate, zip, sorted, reversed in python]] Indhumathy Chelliah; Medium, 30/07/2020
  
 ---- ----
Ligne 124: Ligne 126:
   * Conversion en nombre (donnée numérique créée à partir d'une chaîne de caractères) : int("587"), float("3.14")   * Conversion en nombre (donnée numérique créée à partir d'une chaîne de caractères) : int("587"), float("3.14")
   * Pour la concaténation d'une liste de chaîne, la fonction join est plus adaptée que "+" (cf. [[https://towardsdatascience.com/do-not-use-to-join-strings-in-python-f89908307273|ici]]) :    * Pour la concaténation d'une liste de chaîne, la fonction join est plus adaptée que "+" (cf. [[https://towardsdatascience.com/do-not-use-to-join-strings-in-python-f89908307273|ici]]) : 
-<code>+<code python>
 strings = ['A', 'bac', 'cali', 'jkppl'] strings = ['A', 'bac', 'cali', 'jkppl']
 text = ''.join(strings) text = ''.join(strings)
Ligne 145: Ligne 147:
 string.printable # = digits + ascii_letters + punctuation + whitespace string.printable # = digits + ascii_letters + punctuation + whitespace
 </code> </code>
 +
 +=== Modifications, recherches, index, vérifications,... ===
 +<code python>
 +s.capitalize() # captilizes (first character becomes uppercase) the string
 +s.lower() # all characters become lowercase
 +s.casefold() # more rigorous lowercase (languages other than English are covered)
 +s.upper() # all characters become uppercase
 +
 +s.count(sub) # count occurences of substring sub in s
 +s.count(sub, start) # count occurences of substring sub starting from start position in string s
 +s.count(sub, start, end) # count occurences of substring sub from start to end — 1 position in string s
 +s.find(sub) # returns index of first occurence of substring sub in s, return -1 if not found
 +s.find(sub, start) # returns index of first occurence of substring sub starting from start position in string s, returns -1 if not found
 +s.find(sub, start, end) # returns index of first occurence of substring sub from start to end — 1 position in string s, return -1 if not found
 +s.index(sub) # returns index of first occurence of substring sub in s, raises error if not found
 +s.index(sub, start) # returns index of first occurence of substring sub starting from start position in string s, raises error if not found
 +s.index(sub, start, end) # returns index of first occurence of substring sub from start to end — 1 position in string s, raises error if not found
 +len(str) # returns length of string
 +
 +s.startswith(prefix) # checks if s starts with prefix
 +s.startswith(prefix, start) # checks if s starts with prefix starting from start position
 +s.startswith(prefix, start, end) # checks if s starts with prefix starting from start position until end — 1 position
 +s.endswith(suffix) # checks if s ends with suffix
 +s.endswith(suffix, start) # checks if s ends with suffix starting from start position
 +s.endswith(suffix, start, end) # checks if s ends with suffix starting from start position until end — 1 position
 +s.isalnum() # checks if string is alphanumeric
 +s.isalpha() # checks if string contains only alphabets
 +s.isnumeric() # checks if string contains only numbers
 +s.islower() # checks if all alphabets in string s are lowercase
 +s.isupper() # checks if all alphabets in string s are uppercase
 +s.isspace() # checks if s is a space character
 +
 +s.replace(old, new) # replaces substring old with substring new
 +s.replace(old, new, count) # replace substring old with substring new for count number of times starting from left side of string s
 +s.ljust(width) # puts width — len(s) spaces on the right side of string s
 +s.ljust(width, fillchar=c) # puts character c width — len(s) times on the right side of string s 
 +s.rjust(width) # puts width — len(s) spaces on the left side of string s
 +s.rjust(width, fillchar=c) # puts character c width — len(s) times on the left side of string s
 +s.strip() # all spaces gone left and right both sides of string s
 +s.lstrip() # all spaces gone on left side of string s 
 +s.rstrip() # all spaces gone on right side of string s
 +s.strip(k) # all substrings k gone left and right both sides of string s
 +s.lstrip(k) # all substrings k gone on left side of string s
 +s.rstrip(k) # all substrings k gone on right side of string s
 +s.split(‘,’) # splits the string by ‘,’; returns a list
 +s.split(‘::’) # splits the string by ‘::’; returns a list 
 +s.split(‘ ‘) # splits the string by ‘ ‘; returns a list
 +s.zfill(width) # adds width — len(s) zeros on the left side; if a +/- sign is there then zeros are added after it
 +
 +s.join(l) # joins a list or string l with substring s
 +</code>
 +
 +=== Applications à la détection de palindromes et anagrammes ===
 +
 +
 +<code python string-palindrome-01.py>
 +#!/usr/bin/env python3
 +# -*- coding: utf-8 -*-
 +"""
 +Created on Mon Jan 25 10:58:37 2021
 +
 +@author: villersd
 +
 +Un palindrome est un texte ou une séquence plus générale (notes de musique,
 +code génétique,...), dont l'ordre des lettres (ou des notes,...) reste le même
 +qu'on le lise de gauche à droite ou de droite à gauche.
 +Source : https://fr.wikipedia.org/wiki/Palindrome
 +"""
 +import unicodedata
 +
 +def palindrome(string_to_check):
 +    if string_to_check.lower().replace(' ', '') == string_to_check.lower().replace(' ', '')[::-1]:
 +        return True
 +    else:
 +        return False
 +
 +def remove_accents(input_str):
 +    """
 +    Les lettres accentuées viennent compliquer le problème...
 +    cf. https://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-normalize-in-a-python-unicode-string
 +    """
 +    nfkd_form = unicodedata.normalize('NFKD', input_str)
 +    return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
 +
 +
 +string0 = 'Esope reste ici et se repose'
 +print(string0, palindrome(string0))
 +
 +string1 = 'Ésope reste ici et se repose'
 +print(string1, palindrome(string1))
 +
 +print(string1, remove_accents(string1), palindrome(remove_accents(string1)))
 +
 +</code>
 +
 +<code python string-anagramme-00.py>
 +#!/usr/bin/env python3
 +# -*- coding: utf-8 -*-
 +"""
 +Created on Mon Jan 25 11:42:18 2021
 +
 +@author: villersd
 +
 +Une anagramme est un mot ou une expression obtenu en permutant les lettres
 +d'un mot ou d'une expression de départ
 +Source : https://fr.wikipedia.org/wiki/Anagramme
 +"""
 +string1 = 'manoir'
 +string2 = 'romain'
 +
 +print(string1, sorted(string1))
 +print(string2, sorted(string2))
 +
 +# exercice : utiliser cette fonction sorted() et appliquer les transformations
 +# de la fonction de vérification de palindromes pour détecter une anagramme.
 +
 +</code>
 +
  
 === Références === === Références ===
Ligne 281: Ligne 401:
  
  
-Consulter la [[https://docs.python.org/2/library/collections.html|documentation officielle]], et ces liens ([[http://pymbook.readthedocs.org/en/latest/collections.html|1]][[https://pymotw.com/2/collections/counter.html|2]], [[https://dzone.com/articles/python-201-whats-a-deque|3]][[https://towardsdatascience.com/the-most-undervalued-standard-python-library-14021632f692|4]])+  * Consulter la [[https://docs.python.org/2/library/collections.html|documentation officielle]], et ces liens 
 +    * [[http://pymbook.readthedocs.org/en/latest/collections.html]] 
 +    * [[https://pymotw.com/2/collections/counter.html] 
 +    * [[https://dzone.com/articles/python-201-whats-a-deque|Python 201: What’s a Deque?]] 
 +    * [[https://towardsdatascience.com/the-most-undervalued-standard-python-library-14021632f692|The Most Undervalued Standard Python Library Collections for data scientists]] Tyler Folkman, Medium, Oct 26, 2019 (video) 
 +    * [[https://levelup.gitconnected.com/introducing-high-performance-datatypes-in-python-with-the-collections-library-3d8c334827a5|Introducing high-performance datatypes in Python with the collections library]] George Seif, Medium, Oct 15, 2019
  
 Des types non intégrés par défaut dans Python peuvent facilement être implémentés, en utilisant les types répandus. C'est pas exemple le cas des [[https://fr.wikipedia.org/wiki/Arbre_enracin%C3%A9|arbres]] (informatique, théorie des graphes) : Des types non intégrés par défaut dans Python peuvent facilement être implémentés, en utilisant les types répandus. C'est pas exemple le cas des [[https://fr.wikipedia.org/wiki/Arbre_enracin%C3%A9|arbres]] (informatique, théorie des graphes) :
Ligne 584: Ligne 709:
   * Pour en savoir plus, consultez la page [[https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files]].   * Pour en savoir plus, consultez la page [[https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files]].
   * [[https://medium.com/better-programming/a-cheat-sheet-on-reading-and-writing-files-in-python-e78297adf413|A Cheat Sheet on Reading and Writing Files in Python - Quick reference on how to read and write files]] Yong Cui, Medium, 13/01/2020   * [[https://medium.com/better-programming/a-cheat-sheet-on-reading-and-writing-files-in-python-e78297adf413|A Cheat Sheet on Reading and Writing Files in Python - Quick reference on how to read and write files]] Yong Cui, Medium, 13/01/2020
 +  * [[https://medium.com/techtofreedom/file-handling-in-python-daee4586a64|File Handling in Python]] Yang Zhou, Medium, 25/04/2020
 +
  
  
  • teaching/progappchim/notions_fondamentales.txt
  • Dernière modification : 2023/05/03 08:39
  • de villersd