builtins.object builtins.str
class str(builtins.object):
>>> s = 'Un message' >>> s 'Un message' >>> type(s) <class 'str'> >>> s = "Un autre message" >>> s 'Un autre message' >>> type(s) <class 'str'> >>>
Dans une chaîne de caractères, vous pouvez utiliser des séquences particulières : elles sont introduites par un caractère \
.
Voici quelques séquences utiles.
>>> import math >>> s = "\u03c0 == %f" % math.pi >>> s 'π == 3.141593' >>> print("\a") # Mettre le son
Vous pouvez aussi définir des « raw strings » (des chaînes brutes). Dans ce cas, les séquences débutant par le caractère \
n'auront
plus aucune signification particulière. Pour introduire une raw string, il faut utiliser un simple caractère r
(pour raw), placé devant la chaîne.
>>> path = "C:\newFolder\truc.txt" >>> print(path) C: ewFolder ruc.txt >>> path = r"C:\newFolder\truc.txt" >>> print(path) C:\newFolder\truc.txt >>>
Il existe encore un autre type de chaînes de caractères : les chaînes multi-lignes. On introduit une telle chaîne par trois simples quotes ou trois doubles quotes. Vous devez terminer la chaîne multi-ligne par la même séquence de caractères que celle utilisée en début de chaîne.
>>> usage = """Bienvenue dans ma super Application. ... version 1.0 - KooR.fr - 2020""" >>> print(usage) Bienvenue dans ma super Application. version 1.0 - KooR.fr - 2020 >>>
Vous pouvez cumuler ces possibilités pour définir une chaîne brute multi-ligne : r"""The content ... """
.
>>> original = "Hello World!" >>> original 'Hello World!' >>> modified = original.upper() >>> modified 'HELLO WORLD!' >>> original 'Hello World!' >>> original[0] 'H' >>> original[0] = "Z" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment >>>
Enfin, notez qu'il est possible de convertir n'importe quelle donnée Python en une chaîne de caractères. Pour ce faire, il suffit de construire une nouvelle
instance de la classe str
en passant en paramètre la donnée à convertir. Voici un petit exemple.
>>> intValue = 123 >>> message = "Valeur == " + str(intValue) >>> print(message) Valeur == 123 >>>
str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.
1 2 3 4 5 6 7 8 9 |
#!/usr/bin/python3 first_name = input("Veuillez saisir votre prénom : ") first_name = first_name.lower() last_name = input("Veuillez saisir votre nom : ") last_name = last_name.upper() print("Welcome %s %s" % (first_name, last_name)) |
Et voici les résultats produits par cet exemple.
Veuillez saisir votre prénom : James Veuillez saisir votre nom : Bond Welcome james BOND
Signature du constructeur | Description |
---|---|
__new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. [extrait de __new__.__doc__] |
__init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. [extrait de __init__.__doc__] |
Signature de l'opérateur | Description |
---|---|
__add__(self, value) | Return self+value. [extrait de __add__.__doc__] |
__contains__(self, key) | Return key in self. [extrait de __contains__.__doc__] |
__eq__(self, value) | Return self==value. [extrait de __eq__.__doc__] |
__ge__(self, value) | Return self>=value. [extrait de __ge__.__doc__] |
__getitem__(self, key) | Return self[key]. [extrait de __getitem__.__doc__] |
__gt__(self, value) | Return self>value. [extrait de __gt__.__doc__] |
__le__(self, value) | Return self<=value. [extrait de __le__.__doc__] |
__lt__(self, value) | Return self<value. [extrait de __lt__.__doc__] |
__mod__(self, value) | Return self%value. [extrait de __mod__.__doc__] |
__mul__(self, value) | Return self*value. [extrait de __mul__.__doc__] |
__ne__(self, value) | Return self!=value. [extrait de __ne__.__doc__] |
__rmod__(self, value) | Return value%self. [extrait de __rmod__.__doc__] |
__rmul__(self, value) | Return value*self. [extrait de __rmul__.__doc__] |
Signature de la méthode | Description |
---|---|
__format__(self, format_spec) | Return a formatted version of the string as described by format_spec. [extrait de __format__.__doc__] |
__getattribute__(self, name) | Return getattr(self, name). [extrait de __getattribute__.__doc__] |
__getnewargs__ | |
__hash__(self) | Return hash(self). [extrait de __hash__.__doc__] |
__iter__(self) | Implement iter(self). [extrait de __iter__.__doc__] |
__len__(self) | Return len(self). [extrait de __len__.__doc__] |
__repr__(self) | Return repr(self). [extrait de __repr__.__doc__] |
__sizeof__(self) | Return the size of the string in memory, in bytes. [extrait de __sizeof__.__doc__] |
__str__(self) | Return str(self). [extrait de __str__.__doc__] |
![]() |
|
![]() lower . |
|
![]() width avec son contenu centré. |
|
![]() |
|
![]() |
|
![]() |
|
![]() |
|
![]() |
|
![]() |
|
![]() format mais en utilisant un
dictionnaire comme source de données. |
|
![]() |
|
![]() |
|
isalpha(self) | Return True if the string is an alphabetic string, False otherwise. [extrait de isalpha.__doc__] |
isascii(self) | Return True if all characters in the string are ASCII, False otherwise. [extrait de isascii.__doc__] |
isdecimal(self) | Return True if the string is a decimal string, False otherwise. [extrait de isdecimal.__doc__] |
isdigit(self) | Return True if the string is a digit string, False otherwise. [extrait de isdigit.__doc__] |
isidentifier(self) | Return True if the string is a valid Python identifier, False otherwise. [extrait de isidentifier.__doc__] |
islower(self) | Return True if the string is a lowercase string, False otherwise. [extrait de islower.__doc__] |
isnumeric(self) | Return True if the string is a numeric string, False otherwise. [extrait de isnumeric.__doc__] |
isprintable(self) | Return True if the string is printable, False otherwise. [extrait de isprintable.__doc__] |
isspace(self) | Return True if the string is a whitespace string, False otherwise. [extrait de isspace.__doc__] |
istitle(self) | Return True if the string is a title-cased string, False otherwise. [extrait de istitle.__doc__] |
isupper(self) | Return True if the string is an uppercase string, False otherwise. [extrait de isupper.__doc__] |
join(self, iterable) | Concatenate any number of strings. [extrait de join.__doc__] |
ljust(self, width, fillchar=' ') | Return a left-justified string of length width. [extrait de ljust.__doc__] |
![]() |
|
![]() |
|
maketrans | Return a translation table usable for str.translate(). [extrait de maketrans.__doc__] |
partition(self, sep) | Partition the string into three parts using the given separator. [extrait de partition.__doc__] |
removeprefix(self, prefix) | Return a str with the given prefix string removed if present. [extrait de removeprefix.__doc__] |
removesuffix(self, suffix) | Return a str with the given suffix string removed if present. [extrait de removesuffix.__doc__] |
![]() |
|
![]() |
|
![]() |
|
rjust(self, width, fillchar=' ') | Return a right-justified string of length width. [extrait de rjust.__doc__] |
rpartition(self, sep) | Partition the string into three parts using the given separator. [extrait de rpartition.__doc__] |
rsplit(self, /, sep=None, maxsplit=-1) | Return a list of the substrings in the string, using sep as the separator string. [extrait de rsplit.__doc__] |
![]() |
|
split(self, /, sep=None, maxsplit=-1) | Return a list of the substrings in the string, using sep as the separator string. [extrait de split.__doc__] |
splitlines(self, /, keepends=False) | Return a list of the lines in the string, breaking at line boundaries. [extrait de splitlines.__doc__] |
![]() |
|
![]() |
|
![]() |
|
![]() |
|
translate(self, table) | Replace each character in the string using the given translation table. [extrait de translate.__doc__] |
![]() |
|
zfill(self, width) | Pad a numeric string with zeros on the left, to fill a field of the given width. [extrait de zfill.__doc__] |
Améliorations / Corrections
Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.
Emplacement :
Description des améliorations :