Inbyggda typer¶
I följande avsnitt beskrivs de standardtyper som finns inbyggda i tolken.
De viktigaste inbyggda typerna är numeriska, sekvenser, mappningar, klasser, instanser och undantag.
Vissa samlingsklasser är mutabla. De metoder som lägger till, subtraherar eller omorganiserar sina medlemmar på plats, och inte returnerar ett specifikt objekt, returnerar aldrig själva samlingsinstansen utan None.
Vissa operationer stöds av flera objekttyper; i synnerhet kan praktiskt taget alla objekt jämföras med avseende på likhet, testas för sanningsvärde och konverteras till en sträng (med funktionen repr() eller den något annorlunda funktionen str()). Den senare funktionen används implicit när ett objekt skrivs ut med funktionen print().
Test av sanning och värde¶
Alla objekt kan testas för sanningsvärde, för användning i ett if eller while villkor eller som operand i de booleska operationerna nedan.
By default, an object is considered true unless its class defines either a
__bool__() method that returns False or a
__len__() method that
returns zero, when called with the object. [1] If one of the methods raises an
exception when called, the exception is propagated and the object does
not have a truth value (for example, NotImplemented).
Here are most of the built-in objects considered false:
konstanter som definieras som falska:
NoneochFalsenoll av valfri numerisk typ:
0,0.0,0j,Decimal(0),Fraktion(0, 1)tomma sekvenser och samlingar:
'',(),[],{},set(),range(0)
Operationer och inbyggda funktioner som har ett booleskt resultat returnerar alltid 0 eller False för false och 1 eller True för true, om inget annat anges. (Viktigt undantag: de booleska operationerna eller och och returnerar alltid en av sina operander)
Booleska operationer — and, or, not¶
Dessa är de booleska operationerna, ordnade efter stigande prioritet:
Operation |
Resultat |
Anteckningar |
|---|---|---|
|
om x är sant, då x, annars y |
(1) |
|
om x är falskt, då x, annars y |
(2) |
|
om x är falskt, då |
(3) |
Anteckningar:
Detta är en kortslutningsoperator, vilket innebär att den bara utvärderar det andra argumentet om det första är falskt.
Detta är en kortslutningsoperator, vilket innebär att den bara utvärderar det andra argumentet om det första är sant.
nothar lägre prioritet än icke booleska operatorer, sånot a == btolkas somnot (a == b), ocha == not bär ett syntaxfel.
Jämförelser¶
Det finns åtta jämförelseoperationer i Python. De har alla samma prioritet (som är högre än den för de booleska operationerna). Jämförelser kan kedjas godtyckligt; till exempel är x < y <= z ekvivalent med x < y och y <= z, förutom att y bara utvärderas en gång (men i båda fallen utvärderas z inte alls när x < y visar sig vara falskt).
I denna tabell sammanfattas jämförelseoperationerna:
Operation |
Betydelse |
|---|---|
|
strikt mindre än |
|
mindre än eller lika med |
|
strikt större än |
|
större än eller lika med |
|
lika |
|
är inte lika med |
|
objektets identitet |
|
förnekad objektsidentitet |
Unless stated otherwise, objects of different types never compare equal.
The == operator is always defined but for some object types (for example,
class objects) is equivalent to is. The <, <=, > and >=
operators are only defined where they make sense; for example, they raise a
TypeError exception when one of the arguments is a complex number.
Icke-identiska instanser av en klass jämförs normalt som icke-jämlika om inte klassen definierar metoden __eq__().
Instanser av en klass kan inte ordnas med avseende på andra instanser av samma klass eller andra typer av objekt, såvida inte klassen definierar tillräckligt många av metoderna __lt__(), __le__(), __gt__(), och __ge__() (i allmänhet räcker det med __lt__() och __eq__(), om man vill ha de konventionella betydelserna av jämförelseoperatorerna).
Beteendet hos operatorerna is och is not kan inte anpassas; de kan också tillämpas på två valfria objekt och aldrig ge upphov till ett undantag.
Ytterligare två operationer med samma syntaktiska prioritet, in och not in, stöds av typer som är iterable eller implementerar metoden __contains__().
Numeriska typer — int, float, complex¶
Det finns tre olika numeriska typer: integrer, flytande tal och komplexa tal. Dessutom är booleaner en subtyp av heltal. Heltal har obegränsad precision. Flyttal implementeras vanligtvis med double i C; information om precisionen och den interna representationen av flyttal för den maskin som ditt program körs på finns i sys.float_info. Komplexa tal har en reell del och en imaginär del, som var och en är ett flyttal. För att extrahera dessa delar från ett komplext tal z, använd z.real och z.imag. (Standardbiblioteket innehåller de ytterligare numeriska typerna fractions.Fraction, för rationella tal, och decimal.Decimal, för flyttal med precision som kan definieras av användaren)
Tal skapas av numeriska literaler eller som resultat av inbyggda funktioner och operatorer. Heltalslitteraler utan utsmyckning (inklusive hex-, oktal- och binära tal) ger heltal. Numeriska literaler som innehåller en decimalpunkt eller ett exponenttecken ger flyttal. Om du lägger till 'j' eller 'J' till en numerisk literal får du ett imaginärt tal (ett komplext tal med en reell del på noll) som du kan lägga till ett heltal eller en float för att få ett komplext tal med en reell och en imaginär del.
Konstruktörerna int(), float() och complex() kan användas för att producera tal av en viss typ.
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different built-in numeric types, the operand with the ”narrower” type is widened to that of the other:
Om båda argumenten är komplexa tal utförs ingen konvertering;
om något av argumenten är ett komplext tal eller ett flyttal, konverteras det andra till ett flyttal;
i annat fall måste båda vara heltal och ingen konvertering behövs.
Arithmetic with complex and real operands is defined by the usual mathematical formula, for example:
x + komplex(u, v) = komplex(x + u, v)
x * komplex(u, v) = komplex(x * u, x * v)
En jämförelse mellan tal av olika typer beter sig som om det var de exakta värdena för dessa tal som jämfördes. [2]
Alla numeriska typer (utom komplexa) stöder följande operationer (för prioriteringar av operationerna, se Operator precedence):
Operation |
Resultat |
Anteckningar |
Fullständig dokumentation |
|---|---|---|---|
|
summan av x och y |
||
|
skillnaden mellan x och y |
||
|
produkten av x och y |
||
|
kvot av x och y |
||
|
golvad kvot av x och y |
(1)(2) |
|
|
återstoden av |
(2) |
|
|
x negerad |
||
|
x oförändrad |
||
|
absolut värde eller magnitud av x |
||
|
x omvandlad till heltal |
(3)(6) |
|
|
x omvandlad till flyttal |
(4)(6) |
|
|
ett komplext tal med realdel re, imaginärdel im. im är som standard noll. |
(6) |
|
|
konjugat av det komplexa talet c |
||
|
paret |
(2) |
|
|
x till potensen y |
(5) |
|
|
x till potensen y |
(5) |
Anteckningar:
Kallas även heltalsdivision. För operander av typen
inthar resultatet typenint. För operander av typenfloathar resultatet typenfloat. I allmänhet är resultatet ett helt heltal, även om resultatets typ inte nödvändigtvis ärint. Resultatet är alltid avrundat mot minus oändligheten:1//2är0,(-1)//2är\-1,1//(-2)är\-1och(-1)//(-2)är0.Inte för komplexa tal. Konvertera istället till flyttal med
abs()om det är lämpligt.Konvertering från
floattillinttrunkerar och kastar bort bråkdelen. Se funktionernamath.floor()ochmath.ceil()för alternativa omvandlingar.float accepterar också strängarna ”nan” och ”inf” med ett valfritt prefix ”+” eller ”-” för Not a Number (NaN) och positiv eller negativ oändlighet.
Python definierar
pow(0, 0)och0 ** 0som1, vilket är vanligt för programmeringsspråk.De numeriska literaler som accepteras inkluderar siffrorna
0till9eller någon Unicode-ekvivalent (kodpunkter med egenskapenNd).Se the Unicode Standard för en fullständig lista över kodpunkter med egenskapen
Nd.
Alla numbers.Real-typer (int och float) innehåller också följande operationer:
Operation |
Resultat |
|---|---|
x trunkerad till |
|
x avrundat till n siffror, avrundning hälften till jämnt. Om n utelämnas är standardvärdet 0. |
|
den största |
|
den minsta |
För ytterligare numeriska operationer, se modulerna math och cmath.
Bitvisa operationer på heltalstyper¶
Bitvisa operationer är bara meningsfulla för heltal. Resultatet av bitvisa operationer beräknas som om de utförts i tvåkomplement med ett oändligt antal teckenbitar.
Prioriteringarna för de binära bitvisa operationerna är alla lägre än de numeriska operationerna och högre än jämförelserna; den unära operationen ~ har samma prioritet som de andra unära numeriska operationerna (+ och \-).
I denna tabell listas de bitvisa operationerna sorterade i stigande prioritetsordning:
Operation |
Resultat |
Anteckningar |
|---|---|---|
|
bitvis or av x och y |
(4) |
|
bitvis exklusivt eller av x och y |
(4) |
|
bitvis och av x och y |
(4) |
|
x vänsterförskjutet med n bitar |
(1)(2) |
|
x högerförskjutet med n bitar |
(1)(3) |
|
bitarna i x inverterade |
Anteckningar:
Negativa skifträkningar är olagliga och orsakar ett
ValueError.En vänsterförskjutning med n bitar är likvärdig med multiplikation med
pow(2, n).En högerförskjutning med n bitar motsvarar en vågdivision med
pow(2, n).Att utföra dessa beräkningar med minst en extra teckenförlängningsbit i en ändlig tvåkomplementrepresentation (en fungerande bitbredd på
1 + max(x.bit_length(), y.bit_length())eller mer) är tillräckligt för att få samma resultat som om det fanns ett oändligt antal teckenbitar.
Ytterligare metoder för heltalstyper¶
Typen int implementerar numbers.Integral abstract base class. Dessutom tillhandahåller den några fler metoder:
- int.bit_length()¶
Returnerar det antal bitar som krävs för att representera ett heltal i binär form, exklusive tecken och inledande nollor:
>>> n = -37 >>> bin(n) '-0b100101' >>> n.bit_length() 6
Närmare bestämt, om
xinte är noll, så ärx.bit_length()det unika positiva heltaletkså att2**(k-1) <= abs(x) < 2**k. På motsvarande sätt gäller att närabs(x)är tillräckligt litet för att ha en korrekt avrundad logaritm, så ärk = 1 + int(log(abs(x), 2)). Omxär noll, så returnerarx.bit_length()0.Motsvarar:
def bit_längd(self): s = bin(self) # binär representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # ta bort ledande nollor och minustecken return len(s) # len('100101') --> 6
Added in version 3.1.
- int.bit_count()¶
Returnerar antalet ettor i den binära representationen av heltalets absoluta värde. Detta är också känt som populationsantalet. Exempel:
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3
Motsvarar:
def bit_count(self): return bin(self).count("1")
Added in version 3.10.
- int.to_bytes(length=1, byteorder='big', *, signed=False)¶
Returnerar en array av bytes som representerar ett heltal.
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'
Heltalet representeras med längd byte och standardvärdet är 1. Ett
OverflowErroruppstår om heltalet inte kan representeras med det givna antalet byte.Argumentet byteorder bestämmer den byteordning som används för att representera heltalet, och standardvärdet är
"big". Om byteorder är"big"ligger den mest signifikanta byten i början av bytearrayen. Om byteorder är"little"ligger den mest signifikanta byten i slutet av bytearrayen.Argumentet signed avgör om tvåkomplement används för att representera heltalet. Om signed är
Falseoch ett negativt heltal anges, uppstår ettOverflowError. Standardvärdet för signed ärFalse.Standardvärdena kan användas för att enkelt omvandla ett heltal till ett objekt med en byte:
>>> (65).to_bytes() b'A'
När du använder standardargumenten ska du dock inte försöka konvertera ett värde som är större än 255, för då får du ett
OverflowError.Motsvarar:
def to_bytes(n, length=1, byteorder='big', signed=False): om byteorder == 'liten': order = intervall(längd) elif byteorder == 'stor': ordning = omvänd(intervall(längd)) else: raise ValueError("byteorder måste vara antingen 'liten' eller 'stor'") return bytes((n >> i*8) & 0xff for i in order)
Added in version 3.2.
Förändrat i version 3.11: Lagt till standardargumentvärden för
lengthochbyteorder.
- classmethod int.from_bytes(bytes, byteorder='big', *, signed=False)¶
Returnerar det heltal som representeras av den givna arrayen av bytes.
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680
Argumentet bytes måste antingen vara ett bytesliknande objekt eller en iterabel som producerar bytes.
Argumentet byteorder bestämmer den byteordning som används för att representera heltalet, och standardvärdet är
"big". Om byteorder är"big"ligger den mest signifikanta byten i början av bytearrayen. Om byteorder är"little"ligger den mest betydelsefulla byten i slutet av bytearrayen. Om du vill begära värdsystemets inbyggda byteordning använder dusys.byteordersom värde för byteordningen.Argumentet signed anger om tvåkomplement ska användas för att representera heltalet.
Motsvarar:
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(byte) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder måste vara antingen 'liten' eller 'stor'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) om signerad och little_ordered och (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) returnera n
Added in version 3.2.
Förändrat i version 3.11: Lagt till standardargumentvärde för
byteorder.
- int.as_integer_ratio()¶
Returnerar ett par heltal vars kvot är lika med det ursprungliga heltalet och har en positiv nämnare. Heltalsförhållandet mellan heltal (hela tal) är alltid heltalet i täljaren och
1i nämnaren.Added in version 3.8.
- int.is_integer()¶
Returnerar
True. Existerar för kompatibilitet medfloat.is_integer().Added in version 3.12.
Ytterligare metoder på Float¶
Typen float implementerar numbers.Real abstract base class. float har också följande ytterligare metoder.
- classmethod float.from_number(x)¶
Klassmetod för att returnera ett flyttal konstruerat från ett tal x.
Om argumentet är ett heltal eller ett flyttal, returneras ett flyttal med samma värde (inom Pythons flyttalsprecision). Om argumentet ligger utanför intervallet för en Python-flottör, kommer ett
OverflowErroratt uppstå.För ett allmänt Python-objekt
xdelegerarfloat.from_number(x)tillx.__float__(). Om__float__()inte är definierad faller den tillbaka till__index__().Added in version 3.14.
- float.as_integer_ratio()¶
Returnerar ett par heltal vars kvot är exakt lika med den ursprungliga floaten. Kvoten är i lägsta termer och har en positiv nämnare. Utlöser
OverflowErrorpå oändligheter och ettValueErrorpå NaNs.
- float.is_integer()¶
Returnerar
Trueom float-instansen är finit med integrerat värde, ochFalseannars:>>> (-2.0).is_integer() True >>> (3.2).is_integer() False
Två metoder stöder konvertering till och från hexadecimala strängar. Eftersom Pythons flyttal lagras internt som binära tal innebär konvertering av ett flyttal till eller från en decimal sträng vanligtvis ett litet avrundningsfel. Däremot tillåter hexadecimala strängar exakt representation och specifikation av flyttal. Detta kan vara användbart vid felsökning och i numeriskt arbete.
- float.hex()¶
Returnerar en representation av ett flyttal som en hexadecimal sträng. För finita flyttal kommer denna representation alltid att innehålla en inledande
0xoch en efterföljandepoch exponent.
- classmethod float.fromhex(s)¶
Klassmetod för att returnera den flottör som representeras av en hexadecimal sträng s. Strängen s kan ha inledande och avslutande blanksteg.
Observera att float.hex() är en instansmetod, medan float.fromhex() är en klassmetod.
En hexadecimal sträng har formen:
[tecken] ['0x'] heltal ['.' bråk] ['p' exponent]
där det valfria tecknet kan vara antingen + eller \-, integer och fraction är strängar av hexadecimala siffror, och exponent är ett decimalt heltal med ett valfritt inledande tecken. Versaler är oviktiga och det måste finnas minst en hexadecimal siffra i antingen heltalet eller bråket. Denna syntax liknar den syntax som anges i avsnitt 6.4.4.2 i C99-standarden, och även den syntax som används i Java 1.5 och framåt. I synnerhet kan resultatet från float.hex() användas som en hexadecimal flyttalslitteral i C- eller Java-kod, och hexadecimala strängar som produceras av C:s %a formattecken eller Javas Double.toHexString accepteras av float.fromhex().
Observera att exponenten skrivs i decimalform i stället för hexadecimalform och att den anger med vilken potens 2 koefficienten ska multipliceras. Till exempel representerar den hexadecimala strängen 0x3.a7p10 flyttalstalet (3 + 10./16 + 7./16**2) * 2,0**10, eller 3740,0:
>>> float.fromhex('0x3.a7p10')
3740.0
Genom att tillämpa den omvända konverteringen på 3740.0 får man en annan hexadecimal sträng som representerar samma nummer:
>>> float.hex(3740.0)
'0x1.d380000000000p+11'
Ytterligare metoder för komplexa¶
Typen complex implementerar numbers.Complex abstract base class. complex har även följande ytterligare metoder.
- classmethod complex.from_number(x)¶
Klassmetod för att konvertera ett tal till ett komplext tal.
För ett allmänt Python-objekt
xdelegerarcomplex.from_number(x)tillx.__complex__(). Om__complex__()inte är definierad så faller den tillbaka till__float__(). Om__float__()inte är definierat faller det tillbaka till__index__().Added in version 3.14.
Hashning av numeriska typer¶
För talen x och y, eventuellt av olika typer, är det ett krav att hash(x) == hash(y) när x == y (se __hash__() metoddokumentation för mer information). För att underlätta implementering och effektivitet över en mängd olika numeriska typer (inklusive int, float, decimal.Decimal och fractions.Fraction) Pythons hash för numeriska typer baseras på en enda matematisk funktion som är definierad för alla rationella tal, och gäller därför för alla instanser av int och fractions.Fraction, och alla ändliga instanser av float och decimal.Decimal. I huvudsak ges denna funktion genom reduktion modulo P för ett fast primtal P. Värdet av P görs tillgängligt för Python som attributet modulus av sys.hash_info.
För närvarande används primtalet P = 2**31 - 1 på maskiner med 32-bitars C-längder och P = 2**61 - 1 på maskiner med 64-bitars C-längder.
Här är reglerna i detalj:
Om
x = m / när ett nonnegativt rationellt tal ochninte är delbart medP, definierahash(x)somm * invmod(n, P) % P, därinvmod(n, P)anger inversen avnmoduloP.Om
x = m / när ett nonnegativt rationellt tal ochnär delbart medP(menminte är det) så harningen invers moduloPoch regeln ovan gäller inte; i detta fall definierashash(x)som det konstanta värdetsys.hash_info.inf.Om
x = m / när ett negativt rationellt tal, definierahash(x)som\-hash(-x). Om den resulterande hashen är\-1, ersätt den med\-2.De särskilda värdena
sys.hash_info.infoch\-sys.hash_info.infanvänds som hashvärden för positiv oändlighet respektive negativ oändlighet.För ett
complex-talzkombineras hashvärdena för de reella och imaginära delarna genom att beräknahash(z.real) + sys.hash_info.imag * hash(z.imag), reducerat modulo2**sys.hash_info.widthså att det ligger irange(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1)). Återigen, om resultatet är\-1ersätts det med\-2.
För att klargöra ovanstående regler följer här ett exempel på Python-kod, motsvarande den inbyggda hashen, för att beräkna hashen för ett rationellt tal, float, eller complex:
import sys, matematik
def hash_fraktion(m, n):
"""Beräkna hashvärdet av ett rationellt tal m / n.
Antar att m och n är heltal, med n positivt.
Likvärdig med hash(fractions.Fraction(m, n)).
"""
P = sys.hash_info.modulus
# Ta bort gemensamma faktorer i P. (Onödigt om m och n redan är coprime.)
while m % P == n % P == 0:
m, n = m // P, n // P
om n % P == 0:
hash_värde = sys.hash_info.inf
else:
# Fermats lilla sats: pow(n, P-1, P) är 1, så
# pow(n, P-2, P) ger inversen av n modulo P.
hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
om m < 0:
hash_värde = -hash_värde
om hash_value == -1:
hash_värde = -2
returnera hash_värde
def hash_float(x):
"""Beräkna hashvärdet för en float x."""
om math.isnan(x):
returnera objekt.__hash__(x)
elif math.isinf(x):
return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
annat:
return hash_fraction(*x.as_integer_ratio())
def hash_komplex(z):
"""Beräkna hashvärdet för ett komplext tal z."""
hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
# gör en signerad reduktion modulo 2**sys.hash_info.width
M = 2**(sys.hash_info.width - 1)
hash_värde = (hash_värde & (M - 1)) - (hash_värde & M)
om hash_value == -1:
hash_värde = -2
returnera hash_värde
Booleansk typ - bool¶
Booleaner representerar sanningsvärden. Typen bool har exakt två konstanta instanser: True och False.
Den inbyggda funktionen bool() konverterar ett värde till en boolean, om värdet kan tolkas som ett sanningsvärde (se avsnitt Test av sanning och värde ovan).
För logiska operationer, använd booleska operatorer and, or och not. När man använder de bitvisa operatorerna &, |, ^ på två booleaner returnerar de en bool som motsvarar de logiska operationerna ”and”, ”or”, ”xor”. De logiska operatorerna och, eller och != bör dock föredras framför &, | och ^.
Ersatt sedan version 3.12: Användningen av den bitvisa inversionsoperatorn ~ är föråldrad och kommer att ge upphov till ett fel i Python 3.16.
bool är en underklass till int (se Numeriska typer — int, float, complex). I många numeriska sammanhang beter sig False och True som heltalen 0 respektive 1. Det är dock inte rekommenderat att förlita sig på detta; konvertera explicit med int() istället.
Iterator-typer¶
Python stöder ett koncept för iteration över behållare. Detta implementeras med hjälp av två olika metoder; dessa används för att låta användardefinierade klasser stödja iteration. Sekvenser, som beskrivs mer i detalj nedan, stöder alltid iterationsmetoderna.
En metod måste definieras för containerobjekt för att ge stöd för iterable:
- container.__iter__()¶
Returnerar ett iterator-objekt. Objektet måste ha stöd för iteratorprotokollet som beskrivs nedan. Om en container stöder olika typer av iteration kan ytterligare metoder tillhandahållas för att specifikt begära iteratorer för dessa iterationstyper. (Ett exempel på ett objekt som stöder flera former av iteration är en trädstruktur som stöder både bredd-först- och djup-först-traversering) Denna metod motsvarar
tp_iterslot i typstrukturen för Python-objekt i Python/C API.
Själva iteratorobjekten måste stödja följande två metoder, som tillsammans utgör iteratorprotokollet:
- iterator.__iter__()¶
Returnerar själva iterator-objektet. Detta krävs för att både containers och iteratorer ska kunna användas med
forochinsatserna. Denna metod motsvarartp_iter-platsen i typstrukturen för Python-objekt i Python/C API.
- iterator.__next__()¶
Returnerar nästa objekt från iterator. Om det inte finns några fler objekt, utlöses undantaget
StopIteration. Denna metod motsvarartp_iternext-platsen i typstrukturen för Python-objekt i Python/C API.
Python definierar flera iteratorobjekt för att stödja iteration över allmänna och specifika sekvenstyper, ordböcker och andra mer specialiserade former. De specifika typerna är inte viktiga utöver deras implementering av iteratorprotokollet.
När en iterators __next__()-metod ger upphov till StopIteration, måste den fortsätta att göra det vid efterföljande anrop. Implementationer som inte följer denna egenskap anses vara trasiga.
Typer av generatorer¶
Pythons generator ger ett bekvämt sätt att implementera iteratorprotokollet. Om ett containerobjekts metod __iter__() implementeras som en generator, kommer den automatiskt att returnera ett iteratorobjekt (tekniskt sett ett generatorobjekt) som tillhandahåller metoderna __iter__() och __next__(). Mer information om generatorer finns i dokumentationen för yield-uttrycket.
Sekvenstyper — list, tuple, range¶
Det finns tre grundläggande sekvenstyper: listor, tupler och intervallobjekt. Ytterligare sekvenstyper som är anpassade för bearbetning av binär data och textsträngar beskrivs i särskilda avsnitt.
Vanliga sekvensoperationer¶
Operationerna i följande tabell stöds av de flesta sekvenstyper, både föränderliga och oföränderliga. ABC collections.abc.Sequence tillhandahålls för att göra det enklare att korrekt implementera dessa operationer på anpassade sekvenstyper.
I denna tabell listas sekvensoperationerna sorterade i stigande prioritet. I tabellen är s och t sekvenser av samma typ, n, i, j och k är heltal och x är ett godtyckligt objekt som uppfyller alla typ- och värdebegränsningar som s ställer upp.
Operationerna in och not in har samma prioritet som jämförelseoperationerna. Operationerna + (konkatenering) och * (repetition) har samma prioritet som motsvarande numeriska operationer. [3]
Operation |
Resultat |
Anteckningar |
|---|---|---|
|
|
(1) |
|
|
(1) |
|
sammankopplingen av s och t |
(6)(7) |
|
motsvarar att addera s till sig själv n gånger |
(2)(7) |
|
idet tredje objektet i s, ursprung 0 |
(3)(8) |
|
skiva av s från i till j |
(3)(4) |
|
skiva av s från i till j med steg k |
(3)(5) |
|
längd på s |
|
|
minsta delen av s |
|
|
största posten av s |
Sekvenser av samma typ stöder också jämförelser. Framför allt jämförs tupler och listor lexikografiskt genom att jämföra motsvarande element. Detta innebär att för att jämföra lika måste varje element jämföra lika och de två sekvenserna måste vara av samma typ och ha samma längd. (För fullständig information se Comparisons i språkreferensen)
Framåtriktade och bakåtriktade iteratorer över muterbara sekvenser får tillgång till värden med hjälp av ett index. Detta index kommer att fortsätta att marschera framåt (eller bakåt) även om den underliggande sekvensen muteras. Iteratorn avslutas först när ett IndexError eller ett StopIteration inträffar (eller när indexet sjunker under noll).
Anteckningar:
Medan operationerna
inochnot inendast används för enkel testning av inneslutning i det allmänna fallet, använder vissa specialiserade sekvenser (t.ex.str,bytesochbytearray) dem också för testning av undersekvenser:>>> "gg" in "eggs" True
Värden av n mindre än
0behandlas som0(vilket ger en tom sekvens av samma typ som s). Observera att objekt i sekvensen s inte kopieras; de refereras flera gånger. Detta spökar ofta för nya Python-programmerare; tänk på:>>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[0].append(3) >>> lists [[3], [3], [3]]
Vad som har hänt är att
[]]är en lista med ett element som innehåller en tom lista, så alla tre elementen i[]] * 3är referenser till denna enda tomma lista. Om du ändrar något av elementen ilistsändras denna enda lista. Du kan skapa en lista med olika listor på följande sätt:>>> lists = [[] for i in range(3)] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]
Ytterligare förklaringar finns i FAQ-artikeln How do I create a multidimensional list?.
Om i eller j är negativ, är indexet relativt slutet av sekvensen s:
len(s) + iellerlen(s) + jersätts. Men observera att\-0fortfarande är0.The slice of s from i to j is defined as the sequence of items with index k such that
i <= k < j.If i is omitted or
None, use0.If j is omitted or
None, uselen(s).If i or j is less than
-len(s), use0.If i or j is greater than
len(s), uselen(s).If i is greater than or equal to j, the slice is empty.
Slice av s från i till j med steg k definieras som sekvensen av objekt med index
x = i + n*kså att0 <= n < (j-i)/k. Med andra ord är indexeni,i+k,i+2*k,i+3*koch så vidare, med stopp när j nås (men aldrig inklusive j). När k är positiv reduceras i och j tilllen(s)om de är större. När k är negativ reduceras i och j tilllen(s) - 1om de är större. Om i eller j utelämnas eller ärNone, blir de ”slut”-värden (vilket slut beror på tecknet för k). Observera att k inte kan vara noll. Om k ärNonebehandlas det som1.Sammankoppling av oföränderliga sekvenser resulterar alltid i ett nytt objekt. Detta innebär att uppbyggnaden av en sekvens genom upprepad konkatenering får en kvadratisk körtidskostnad i den totala sekvenslängden. För att få en linjär körtidskostnad måste du byta till något av alternativen nedan:
om du sammanfogar
str-objekt kan du bygga en lista och användastr.join()i slutet eller skriva till enio.StringIO-instans och hämta dess värde när du är klarom du konkatenerar
bytes-objekt kan du på samma sätt användabytes.join()ellerio.BytesIO, eller så kan du göra konkatenering på plats med ettbytearray-objekt.bytearray-objekt är muterbara och har en effektiv mekanism för overallokeringför andra typer, undersök den relevanta klassdokumentationen
Vissa sekvenstyper (t.ex.
range) stöder endast sekvenser av objekt som följer specifika mönster och stöder därför inte sammankoppling eller upprepning av sekvenser.Ett
IndexErroruppstår om i ligger utanför sekvensintervallet.
Sekvensmetoder
Sequence types also support the following methods:
- sequence.count(value, /)¶
Return the total number of occurrences of value in sequence.
- sequence.index(value[, start[, stop])¶
Return the index of the first occurrence of value in sequence.
Raises
ValueErrorif value is not found in sequence.The start or stop arguments allow for efficient searching of subsections of the sequence, beginning at start and ending at stop. This is roughly equivalent to
start + sequence[start:stop].index(value), only without copying any data.Varning
Not all sequence types support passing the start and stop arguments.
Oföränderliga sekvenstyper¶
Den enda operation som oföränderliga sekvenstyper i allmänhet implementerar och som inte också implementeras av föränderliga sekvenstyper är stöd för den inbyggda hash().
Detta stöd gör att oföränderliga sekvenser, t.ex. tuple-instanser, kan användas som dict-nycklar och lagras i set- och frozenset-instanser.
Försök att hasha en oföränderlig sekvens som innehåller värden som inte kan hashas kommer att resultera i TypeError.
Mutabla sekvenstyper¶
Operationerna i följande tabell är definierade för mutabla sekvenstyper. Klassen collections.abc.MutableSequence ABC tillhandahålls för att göra det enklare att korrekt implementera dessa operationer på anpassade sekvenstyper.
I tabellen är s en instans av en föränderlig sekvenstyp, t är ett itererbart objekt och x är ett godtyckligt objekt som uppfyller alla typ- och värdebegränsningar som s ställer (till exempel accepterar bytearray endast heltal som uppfyller värdebegränsningen 0 <= x <= 255).
Operation |
Resultat |
Anteckningar |
|---|---|---|
|
post i i s ska ersättas med x |
|
|
tar bort objekt i av s |
|
|
slice av s från i till j ersätts av innehållet i iterabeln t |
|
|
tar bort elementen i |
|
|
elementen i |
(1) |
|
tar bort elementen i |
|
|
utökar s med innehållet i t (till största delen samma sak som |
|
|
uppdaterar s med dess innehåll upprepade n gånger |
(2) |
Anteckningar:
Om k inte är lika med
1, måste t ha samma längd som den skiva den ersätter.Värdet n är ett heltal eller ett objekt som implementerar
__index__(). Noll och negativa värden på n rensar sekvensen. Objekten i sekvensen kopieras inte; de refereras flera gånger, vilket förklaras förs * nunder Vanliga sekvensoperationer.
Mutable Sequence Methods
Mutable sequence types also support the following methods:
- sequence.append(value, /)¶
Append value to the end of the sequence. This is equivalent to writing
seq[len(seq):len(seq)] = [value].
- sequence.clear()¶
Added in version 3.3.
Remove all items from sequence. This is equivalent to writing
del sequence[:].
- sequence.copy()¶
Added in version 3.3.
Create a shallow copy of sequence. This is equivalent to writing
sequence[:].Råd
The
copy()method is not part of theMutableSequenceABC, but most concrete mutable sequence types provide it.
- sequence.extend(iterable, /)¶
Extend sequence with the contents of iterable. For the most part, this is the same as writing
seq[len(seq):len(seq)] = iterable.
- sequence.insert(index, value, /)¶
Insert value into sequence at the given index. This is equivalent to writing
sequence[index:index] = [value].
- sequence.pop(index=-1, /)¶
Retrieve the item at index and also removes it from sequence. By default, the last item in sequence is removed and returned.
- sequence.remove(value, /)¶
Remove the first item from sequence where
sequence[i] == value.Raises
ValueErrorif value is not found in sequence.
- sequence.reverse()¶
Reverse the items of sequence in place. This method maintains economy of space when reversing a large sequence. To remind users that it operates by side-effect, it returns
None.
Listor¶
Listor är föränderliga sekvenser som vanligtvis används för att lagra samlingar av homogena objekt (där den exakta graden av likhet varierar beroende på tillämpning).
- class list(iterable=(), /)¶
Listor kan byggas upp på flera olika sätt:
Använd ett par hakparenteser för att beteckna den tomma listan:
[]Using square brackets, separating items with commas:
[a],[a, b, c]Using a list comprehension:
[x for x in iterable]Using the type constructor:
list()orlist(iterable)
The constructor builds a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to
iterable[:]. For example,list('abc')returns['a', 'b', 'c']andlist( (1, 2, 3) )returns[1, 2, 3]. If no argument is given, the constructor creates a new empty list,[].Many other operations also produce lists, including the
sorted()built-in.Lists implement all of the common and mutable sequence operations. Lists also provide the following additional method:
- sort(*, key=None, reverse=False)¶
This method sorts the list in place, using only
<comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).sort()accepts two arguments that can only be passed by keyword (keyword-only arguments):key specifies a function of one argument that is used to extract a comparison key from each list element (for example,
key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value ofNonemeans that list items are sorted directly without calculating a separate key value.The
functools.cmp_to_key()utility is available to convert a 2.x style cmp function to a key function.reverse is a boolean value. If set to
True, then the list elements are sorted as if each comparison were reversed.This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use
sorted()to explicitly request a new sorted list instance).The
sort()method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).For sorting examples and a brief sorting tutorial, see Sorting Techniques.
Detaljerad implementering av CPython: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises
ValueErrorif it can detect that the list has been mutated during a sort.
Se även
For detailed information on thread-safety guarantees for list
objects, see Thread safety for list objects.
Tuples¶
Tuples are immutable sequences, typically used to store collections of
heterogeneous data (such as the 2-tuples produced by the enumerate()
built-in). Tuples are also used for cases where an immutable sequence of
homogeneous data is needed (such as allowing storage in a set or
dict instance).
- class tuple(iterable=(), /)¶
Tuples may be constructed in a number of ways:
Using a pair of parentheses to denote the empty tuple:
()Using a trailing comma for a singleton tuple:
a,or(a,)Separating items with commas:
a, b, cor(a, b, c)Using the
tuple()built-in:tuple()ortuple(iterable)
The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example,
tuple('abc')returns('a', 'b', 'c')andtuple( [1, 2, 3] )returns(1, 2, 3). If no argument is given, the constructor creates a new empty tuple,().Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example,
f(a, b, c)is a function call with three arguments, whilef((a, b, c))is a function call with a 3-tuple as the sole argument.Tuples implement all of the common sequence operations.
For heterogeneous collections of data where access by name is clearer than
access by index, collections.namedtuple() may be a more appropriate
choice than a simple tuple object.
Ranges¶
The range type represents an immutable sequence of numbers and is
commonly used for looping a specific number of times in for
loops.
- class range(stop, /)¶
- class range(start, stop, step=1, /)
The arguments to the range constructor must be integers (either built-in
intor any object that implements the__index__()special method). If the step argument is omitted, it defaults to1. If the start argument is omitted, it defaults to0. If step is zero,ValueErroris raised.For a positive step, the contents of a range
rare determined by the formular[i] = start + step*iwherei >= 0andr[i] < stop.For a negative step, the contents of the range are still determined by the formula
r[i] = start + step*i, but the constraints arei >= 0andr[i] > stop.A range object will be empty if
r[0]does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.Ranges containing absolute values larger than
sys.maxsizeare permitted but some features (such aslen()) may raiseOverflowError.Range examples:
>>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> list(range(0, 30, 5)) [0, 5, 10, 15, 20, 25] >>> list(range(0, 10, 3)) [0, 3, 6, 9] >>> list(range(0, -10, -1)) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> list(range(0)) [] >>> list(range(1, 0)) []
Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).
- start¶
The value of the start parameter (or
0if the parameter was not supplied)
- stop¶
The value of the stop parameter
- step¶
The value of the step parameter (or
1if the parameter was not supplied)
The advantage of the range type over a regular list or
tuple is that a range object will always take the same
(small) amount of memory, no matter the size of the range it represents (as it
only stores the start, stop and step values, calculating individual
items and subranges as needed).
Range objects implement the collections.abc.Sequence ABC, and provide
features such as containment tests, element index lookup, slicing and
support for negative indices (see Sekvenstyper — list, tuple, range):
>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18
Testing range objects for equality with == and != compares
them as sequences. That is, two range objects are considered equal if
they represent the same sequence of values. (Note that two range
objects that compare equal might have different start,
stop and step attributes, for example
range(0) == range(2, 1, 3) or range(0, 3, 2) == range(0, 4, 2).)
Förändrat i version 3.2: Implement the Sequence ABC.
Support slicing and negative indices.
Test int objects for membership in constant time instead of
iterating through all items.
Förändrat i version 3.3: Define ’==’ and ’!=’ to compare range objects based on the sequence of values they define (instead of comparing based on object identity).
Se även
The linspace recipe shows how to implement a lazy version of range suitable for floating-point applications.
Text and Binary Sequence Type Methods Summary¶
The following table summarizes the text and binary sequence types methods by category.
Category |
|
|||||||
|---|---|---|---|---|---|---|---|---|
Formatting |
||||||||
Searching and Replacing |
||||||||
Splitting and Joining |
||||||||
String Classification |
||||||||
Case Manipulation |
||||||||
Padding and Stripping |
||||||||
Translation and Encoding |
||||||||
Text Sequence Type — str¶
Textual data in Python is handled with str objects, or strings.
Strings are immutable
sequences of Unicode code points. String literals are
written in a variety of ways:
Single quotes:
'allows embedded "double" quotes'Double quotes:
"allows embedded 'single' quotes"Triple quoted:
'''Three single quotes''',"""Three double quotes"""
Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.
String literals that are part of a single expression and have only whitespace
between them will be implicitly converted to a single string literal. That
is, ("spam " "eggs") == "spam eggs".
See String and Bytes literals for more about the various forms of string literal,
including supported escape sequences, and the r (”raw”) prefix that
disables most escape sequence processing.
Strings may also be created from other objects using the str
constructor.
Since there is no separate ”character” type, indexing a string produces
strings of length 1. That is, for a non-empty string s, s[0] == s[0:1].
Det finns inte heller någon mutabel strängtyp, men str.join() eller io.StringIO kan användas för att effektivt konstruera strängar från flera fragment.
Förändrat i version 3.3: För bakåtkompatibilitet med Python 2-serien är prefixet u återigen tillåtet för stränglitteraler. Det har ingen effekt på betydelsen av stränglitteraler och kan inte kombineras med prefixet r.
- class str(*, encoding='utf-8', errors='strict')¶
- class str(object)
- class str(object, encoding, errors='strict')
- class str(object, *, errors)
Returnerar en sträng-version av objekt. Om object inte anges, returneras den tomma strängen. Annars beror beteendet hos
str()på om encoding eller errors anges, enligt följande.Om varken encoding eller errors anges returnerar
str(object)type(object).__str__(object), vilket är den ”informella” eller snyggt utskrivbara strängrepresentationen av object. För strängobjekt är detta själva strängen. Om object inte har en__str__()-metod, fallerstr()tillbaka till att returnerarepr(object).Om minst en av encoding eller errors anges, bör object vara ett bytes-like object (t.ex.
bytesellerbytearray). I det här fallet, om objekt är ettbytes(ellerbytearray) objekt, så ärstr(bytes, encoding, errors)ekvivalent medbytes.decode(encoding, errors). I annat fall erhålls bytesobjektet som ligger under buffertobjektet innanbytes.decode()anropas. Se Binary Sequence Types — bytes, bytearray, memoryview och Buffer Protocol för information om buffertobjekt.Att skicka ett
bytes-objekt tillstr()utan argumenten encoding eller errors faller under det första fallet av att returnera den informella strängrepresentationen (se även kommandoradsalternativet-btill Python). Till exempel:>>> str(b'Zoot!') "b'Zoot!'"
Mer information om klassen
stroch dess metoder finns i avsnitten Text Sequence Type — str och Strängmetoder nedan. För att skriva ut formaterade strängar, se avsnitten f-strängar och Format string syntax. Dessutom, se avsnittet Text Processing Services.
Strängmetoder¶
Strängar implementerar alla common sekvensoperationer, tillsammans med de ytterligare metoder som beskrivs nedan.
Strängar har också stöd för två typer av strängformatering, en som ger stor flexibilitet och möjlighet till anpassning (se str.format(), Format string syntax och Custom string formatting) och en som baseras på C printf-stilformatering som hanterar ett smalare urval av typer och är något svårare att använda korrekt, men som ofta är snabbare i de fall den kan hantera (strängformatering i stil med printf).
Avsnittet Text Processing Services i standardbiblioteket omfattar ett antal andra moduler som tillhandahåller olika textrelaterade verktyg (inklusive stöd för reguljära uttryck i modulen re).
- str.capitalize()¶
Returnerar en kopia av strängen med första tecknet i versaler och resten i gemener.
Förändrat i version 3.8: Det första tecknet sätts nu i titelbokstäver i stället för versaler. Detta innebär att tecken som digrafer endast får sin första bokstav versaliserad, istället för hela tecknet.
- str.casefold()¶
Returnerar en casefoldad kopia av strängen. Casefoldade strängar kan användas för caseless matchning.
Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter
'ß'is equivalent to"ss". Since it is already lowercase,lower()would do nothing to'ß';casefold()converts it to"ss". For example:>>> 'straße'.lower() 'straße' >>> 'straße'.casefold() 'strasse'
Algoritmen för casefolding beskrivs i avsnitt 3.13 ”Default Case Folding” i Unicode-standarden.
Added in version 3.3.
- str.center(width, fillchar=' ', /)¶
Returnerar centrerad i en sträng av längden bredd. Utfyllnad görs med hjälp av det angivna fillchar (standard är ett ASCII-rymd). Den ursprungliga strängen returneras om width är mindre än eller lika med
len(s). Till exempel:>>> 'Python'.center(10) ' Python ' >>> 'Python'.center(10, '-') '--Python--' >>> 'Python'.center(4) 'Python'
- str.count(sub[, start[, end]])¶
Returnerar antalet icke-överlappande förekomster av substring sub i intervallet [start, slut]. De valfria argumenten start och slut tolkas som i slice-notation.
Om sub är tom, returneras antalet tomma strängar mellan tecknen, vilket är strängens längd plus ett. Till exempel:
>>> 'spam, spam, spam'.count('spam') 3 >>> 'spam, spam, spam'.count('spam', 5) 2 >>> 'spam, spam, spam'.count('spam', 5, 10) 1 >>> 'spam, spam, spam'.count('eggs') 0 >>> 'spam, spam, spam'.count('') 17
- str.encode(encoding='utf-8', errors='strict')¶
Returnerar strängen kodad till
bytes.encoding är som standard
'utf-8'; se Standard Encodings för möjliga värden.errors styr hur kodningsfel ska hanteras. Om
'strict'(standard), kommer ettUnicodeErrorundantag att uppstå. Andra möjliga värden är'ignore','replace','xmlcharrefreplace','backslashreplace'och alla andra namn som registreras viacodecs.register_error(). Se Error Handlers för detaljer.Av prestandaskäl kontrolleras inte värdet på errors om inte ett kodningsfel faktiskt inträffar, Python Development Mode är aktiverat eller en debug build används. Till exempel:
>>> encoded_str_to_bytes = 'Python'.encode() >>> type(encoded_str_to_bytes) <class 'bytes'> >>> encoded_str_to_bytes b'Python'
Förändrat i version 3.1: Stöd för nyckelordsargument har lagts till.
Förändrat i version 3.9: Värdet på errors-argumentet kontrolleras nu i Python Development Mode och i debug mode.
- str.endswith(suffix[, start[, end]])¶
Returnerar
Trueom strängen slutar med det angivna suffixet, annars returnerasFalse. suffix kan också vara en tupel av suffix att leta efter. Med valfri start börjar testet vid den positionen. Med valfri end, sluta jämföra vid den positionen. Att använda start och end är likvärdigt medstr[start:end].endswith(suffix). Till exempel:>>> 'Python'.endswith('on') True >>> 'a tuple of suffixes'.endswith(('at', 'in')) False >>> 'a tuple of suffixes'.endswith(('at', 'es')) True >>> 'Python is amazing'.endswith('is', 0, 9) True
Se även
startswith()ochremovesuffix().
- str.expandtabs(tabsize=8)¶
Returnerar en kopia av strängen där alla tabbtecken ersatts av ett eller flera mellanslag, beroende på aktuell kolumn och angiven tabbstorlek. Tabbpositioner uppstår varje tabsize tecken (standard är 8, vilket ger tabbpositioner i kolumnerna 0, 8, 16 och så vidare). För att expandera strängen sätts den aktuella kolumnen till noll och strängen granskas tecken för tecken. Om tecknet är en tabb (
t) infogas ett eller flera mellanslagstecken i resultatet tills den aktuella kolumnen är lika med nästa tabbposition. (Tabbtecknet i sig kopieras inte.) Om tecknet är en ny rad (\n) eller en retur (\r) kopieras det och den aktuella kolumnen nollställs. Alla andra tecken kopieras oförändrade och den aktuella kolumnen ökas med ett oavsett hur tecknet representeras när det skrivs ut. Till exempel:>>> '01\t012\t0123\t01234'.expandtabs() '01 012 0123 01234' >>> '01\t012\t0123\t01234'.expandtabs(4) '01 012 0123 01234' >>> print('01\t012\n0123\t01234'.expandtabs(4)) 01 012 0123 01234
- str.find(sub[, start[, end]])¶
Returnera det lägsta indexet i strängen där delsträngen sub finns inom segmentet
s[start:end]. Valfria argument start och end tolkas som i segmentnotation. Returnera\-1om sub inte hittas. Till exempel:>>> 'spam, spam, spam'.find('sp') 0 >>> 'spam, spam, spam'.find('sp', 5) 6
- str.format(*args, **kwargs)¶
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces
{}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument. For example:>>> "The sum of 1 + 2 is {0}".format(1+2) 'The sum of 1 + 2 is 3' >>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2) 'The sum of 1 + 2 is 3' >>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody") 'Nobody expects the Spanish Inquisition!'
Se Format string syntax för en beskrivning av de olika formateringsalternativ som kan anges i formatsträngar.
Observera
Vid formatering av ett tal (
int,float,complex,decimal.Decimaloch underklasser) med typenn(ex:'{:n}'.format(1234)), ställer funktionen temporärt inLC_CTYPElocale tillLC_NUMERIClocale för att avkodadecimal_pointochthousands_sepfälten ilocaleconv()om de är icke-ASCII eller längre än 1 byte, ochLC_NUMERIClocale är annorlunda änLC_CTYPElocale. Denna tillfälliga ändring påverkar andra trådar.Förändrat i version 3.7: Vid formatering av ett tal med typen
nställer funktionen i vissa fall tillfälligt inLC_CTYPElocale tillLC_NUMERIClocale.
- str.format_map(mapping, /)¶
Liknar
str.format(**mapping), förutom attmappinganvänds direkt och inte kopieras till endict. Detta är användbart om till exempelmappingär en dict-underklass:>>> class Default(dict): ... def __missing__(self, key): ... return key ... >>> '{name} was born in {country}'.format_map(Default(name='Guido')) 'Guido was born in country'
Added in version 3.2.
- str.index(sub[, start[, end]])¶
Like
find(), but raiseValueErrorwhen the substring is not found. For example:>>> 'spam, spam, spam'.index('spam') 0 >>> 'spam, spam, spam'.index('eggs') Traceback (most recent call last): File "<python-input-0>", line 1, in <module> 'spam, spam, spam'.index('eggs') ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^ ValueError: substring not found
See also
rindex().
- str.isalnum()¶
Return
Trueif all characters in the string are alphanumeric and there is at least one character,Falseotherwise. A charactercis alphanumeric if one of the following returnsTrue:c.isalpha(),c.isdecimal(),c.isdigit(), orc.isnumeric(). For example:>>> 'abc123'.isalnum() True >>> 'abc123!@#'.isalnum() False >>> ''.isalnum() False >>> ' '.isalnum() False
- str.isalpha()¶
Return
Trueif all characters in the string are alphabetic and there is at least one character,Falseotherwise. Alphabetic characters are those characters defined in the Unicode character database as ”Letter”, i.e., those with general category property being one of ”Lm”, ”Lt”, ”Lu”, ”Ll”, or ”Lo”. Note that this is different from the Alphabetic property defined in the section 4.10 ’Letters, Alphabetic, and Ideographic’ of the Unicode Standard. For example:>>> 'Letters and spaces'.isalpha() False >>> 'LettersOnly'.isalpha() True >>> 'µ'.isalpha() # non-ASCII characters can be considered alphabetical too True
See Unicode Properties.
- str.isascii()¶
Return
Trueif the string is empty or all characters in the string are ASCII,Falseotherwise. ASCII characters have code points in the range U+0000-U+007F. For example:>>> 'ASCII characters'.isascii() True >>> 'µ'.isascii() False
Added in version 3.7.
- str.isdecimal()¶
Return
Trueif all characters in the string are decimal characters and there is at least one character,Falseotherwise. Decimal characters are those that can be used to form numbers in base 10, such as U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category ”Nd”. For example:>>> '0123456789'.isdecimal() True >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # Arabic-Indic digits zero to nine True >>> 'alphabetic'.isdecimal() False
- str.isdigit()¶
Returnerar
Trueom alla tecken i strängen är siffror och det finns minst ett tecken, annarsFalse. Siffror omfattar decimala tecken och siffror som kräver särskild hantering, t.ex. upphöjda siffror för kompatibilitet. Detta omfattar siffror som inte kan användas för att bilda tal i bas 10, t.ex. Kharosthi-talen. Formellt sett är en siffra ett tecken som har egenskapsvärdet Numeric_Type=Digit eller Numeric_Type=Decimal.
- str.isidentifier()¶
Returnerar
Trueom strängen är en giltig identifierare enligt språkdefinitionen, avsnitt Names (identifiers and keywords).keyword.iskeyword()kan användas för att testa om strängensär en reserverad identifierare, t.ex.defochclass.Exempel:
>>> from keyword import iskeyword >>> 'hello'.isidentifier(), iskeyword('hello') (True, False) >>> 'def'.isidentifier(), iskeyword('def') (True, True)
- str.islower()¶
Returnerar
Trueom alla tecken med versaler [4] i strängen är gemener och det finns minst ett tecken med versaler,Falseannars.
- str.isnumeric()¶
Return
Trueif all characters in the string are numeric characters, and there is at least one character,Falseotherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. For example:>>> '0123456789'.isnumeric() True >>> '٠١٢٣٤٥٦٧٨٩'.isnumeric() # Arabic-indic digit zero to nine True >>> '⅕'.isnumeric() # Vulgar fraction one fifth True >>> '²'.isdecimal(), '²'.isdigit(), '²'.isnumeric() (False, True, True)
See also
isdecimal()andisdigit(). Numeric characters are a superset of decimal numbers.
- str.isprintable()¶
Returnerar
Trueom alla tecken i strängen är utskrivbara,Falseom den innehåller minst ett icke-utskrivbart tecken.Här betyder ”printable” att tecknet är lämpligt för
repr()att använda i sin utdata; ”non-printable” betyder attrepr()på inbyggda typer kommer att hex-escape tecknet. Det har ingen betydelse för hanteringen av strängar som skrivs tillsys.stdoutellersys.stderr.De tryckbara tecknen är de som i Unicodes teckendatabas (se
unicodedata) har en allmän kategori i gruppen Letter, Mark, Number, Punctuation, or Symbol (L, M, N, P, or S); plus ASCII-rymden 0x20. Icke-tryckbara tecken är de som finns i gruppen Separator eller Annat (Z eller C), förutom ASCII-utrymmet.Till exempel:
>>> ''.isprintable(), ' '.isprintable() (True, True) >>> '\t'.isprintable(), '\n'.isprintable() (False, False)
See also
isspace().
- str.isspace()¶
Returnerar
Trueom det bara finns blankstegstecken i strängen och det finns minst ett tecken,Falseannars.Till exempel:
>>> ''.isspace() False >>> ' '.isspace() True >>> '\t\n'.isspace() # TAB and BREAK LINE True >>> '\u3000'.isspace() # IDEOGRAPHIC SPACE True
Ett tecken är whitespace om det i Unicodes teckendatabas (se
unicodedata) antingen har den allmänna kategorinZs(”Separator, mellanslag”), eller om dess dubbelriktade klass är en avWS,BellerS.See also
isprintable().
- str.istitle()¶
Returnerar
Trueom strängen är en titlecased-sträng och det finns minst ett tecken, till exempel kan versaler bara följa obokstaverade tecken och gemena tecken bara bokstaverade. ReturnerarFalseannars.Till exempel:
>>> 'Spam, Spam, Spam'.istitle() True >>> 'spam, spam, spam'.istitle() False >>> 'SPAM, SPAM, SPAM'.istitle() False
See also
title().
- str.isupper()¶
Returnerar
Trueom alla tecken med versaler [4] i strängen är versaler och det finns minst ett tecken med versaler,Falseannars.>>> 'BANANA'.isupper() True >>> 'banana'.isupper() False >>> 'baNana'.isupper() False >>> ' '.isupper() False
- str.join(iterable, /)¶
Return a string which is the concatenation of the strings in iterable. A
TypeErrorwill be raised if there are any non-string values in iterable, includingbytesobjects. The separator between elements is the string providing this method. For example:>>> ', '.join(['spam', 'spam', 'spam']) 'spam, spam, spam' >>> '-'.join('Python') 'P-y-t-h-o-n'
See also
split().
- str.ljust(width, fillchar=' ', /)¶
Returnerar strängen vänsterställd i en sträng med längden width. Utfyllnad görs med det angivna fillchar (standard är ett ASCII-rymd). Den ursprungliga strängen returneras om width är mindre än eller lika med
len(s).Till exempel:
>>> 'Python'.ljust(10) 'Python ' >>> 'Python'.ljust(10, '.') 'Python....' >>> 'Monty Python'.ljust(10, '.') 'Monty Python'
See also
rjust().
- str.lower()¶
Return a copy of the string with all the cased characters [4] converted to lowercase. For example:
>>> 'Lower Method Example'.lower() 'lower method example'
Den algoritm för gemener som används beskrivs i avsnitt 3.13 ”Default Case Folding” i Unicode-standarden.
- str.lstrip(chars=None, /)¶
Returnerar en kopia av strängen med inledande tecken borttagna. Argumentet chars är en sträng som anger den uppsättning tecken som ska tas bort. Om chars utelämnas eller är
Noneär standardinställningen att ta bort blanksteg. Argumentet chars är inte ett prefix, utan alla kombinationer av dess värden tas bort:>>> ' spacious '.lstrip() 'spacious ' >>> 'www.example.com'.lstrip('cmowz.') 'example.com'
Se
str.removeprefix()för en metod som tar bort en enda prefixsträng i stället för alla tecken i en uppsättning. Till exempel:>>> 'Arthur: three!'.lstrip('Arthur: ') 'ee!' >>> 'Arthur: three!'.removeprefix('Arthur: ') 'three!'
- static str.maketrans(dict, /)¶
- static str.maketrans(from, to, remove='', /)
Denna statiska metod returnerar en översättningstabell som kan användas för
str.translate().Om det bara finns ett argument måste det vara en ordbok som mappar Unicode-ordinaler (heltal) eller tecken (strängar av längd 1) till Unicode-ordinaler, strängar (av godtycklig längd) eller
None. Teckennycklar kommer då att konverteras till ordinaler.Om det finns två argument måste de vara strängar av samma längd, och i den resulterande ordlistan kommer varje tecken i from att mappas till tecknet på samma position i to. Om det finns ett tredje argument måste det vara en sträng, vars tecken kommer att mappas till
Nonei resultatet.
- str.partition(sep, /)¶
Dela strängen vid den första förekomsten av sep och returnera en 3-tupel som innehåller delen före separatorn, själva separatorn och delen efter separatorn. Om separatorn inte hittas returneras en 3-tupel som innehåller själva strängen, följt av två tomma strängar.
Till exempel:
>>> 'Monty Python'.partition(' ') ('Monty', ' ', 'Python') >>> "Monty Python's Flying Circus".partition(' ') ('Monty', ' ', "Python's Flying Circus") >>> 'Monty Python'.partition('-') ('Monty Python', '', '')
See also
rpartition().
- str.removeprefix(prefix, /)¶
If the string starts with the prefix string, return
string[len(prefix):]. Otherwise, return a copy of the original string:>>> 'TestHook'.removeprefix('Test') 'Hook' >>> 'BaseTestCase'.removeprefix('Test') 'BaseTestCase'
Added in version 3.9.
See also
removesuffix()andstartswith().
- str.removesuffix(suffix, /)¶
If the string ends with the suffix string and that suffix is not empty, return
string[:-len(suffix)]. Otherwise, return a copy of the original string:>>> 'MiscTests'.removesuffix('Tests') 'Misc' >>> 'TmpDirMixin'.removesuffix('Tests') 'TmpDirMixin'
Added in version 3.9.
See also
removeprefix()andendswith().
- str.replace(old, new, /, count=-1)¶
Return a copy of the string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced. If count is not specified or
-1, then all occurrences are replaced. For example:>>> 'spam, spam, spam'.replace('spam', 'eggs') 'eggs, eggs, eggs' >>> 'spam, spam, spam'.replace('spam', 'eggs', 1) 'eggs, spam, spam'
Förändrat i version 3.13: count stöds nu som ett nyckelordsargument.
- str.rfind(sub[, start[, end]])¶
Return the highest index in the string where substring sub is found, such that sub is contained within
s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return-1on failure. For example:>>> 'spam, spam, spam'.rfind('sp') 12 >>> 'spam, spam, spam'.rfind('sp', 0, 10) 6
- str.rindex(sub[, start[, end]])¶
Like
rfind()but raisesValueErrorwhen the substring sub is not found. For example:>>> 'spam, spam, spam'.rindex('spam') 12 >>> 'spam, spam, spam'.rindex('eggs') Traceback (most recent call last): File "<stdin-0>", line 1, in <module> 'spam, spam, spam'.rindex('eggs') ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^ ValueError: substring not found
- str.rjust(width, fillchar=' ', /)¶
Returnerar strängen högerställd i en sträng med längden width. Utfyllnad görs med det angivna fillchar (standard är ett ASCII-rymd). Den ursprungliga strängen returneras om width är mindre än eller lika med
len(s).Till exempel:
>>> 'Python'.rjust(10) ' Python' >>> 'Python'.rjust(10, '.') '....Python' >>> 'Monty Python'.rjust(10, '.') 'Monty Python'
- str.rpartition(sep, /)¶
Dela strängen vid den sista förekomsten av sep och returnera en 3-tupel som innehåller delen före separatorn, själva separatorn och delen efter separatorn. Om separatorn inte hittas, returneras en 3-tupel som innehåller två tomma strängar, följt av själva strängen.
Till exempel:
>>> 'Monty Python'.rpartition(' ') ('Monty', ' ', 'Python') >>> "Monty Python's Flying Circus".rpartition(' ') ("Monty Python's Flying", ' ', 'Circus') >>> 'Monty Python'.rpartition('-') ('', '', 'Monty Python')
See also
partition().
- str.rsplit(sep=None, maxsplit=-1)¶
Returnerar en lista med orden i strängen, med sep som avgränsningssträng. Om maxsplit anges görs högst maxsplit uppdelningar, de högst till höger. Om sep inte anges eller om
None, är alla strängar med blanksteg en separator. Förutom att dela upp från höger, beter sigrsplit()somsplit()som beskrivs i detalj nedan.
- str.rstrip(chars=None, /)¶
Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or
None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped. For example:>>> ' spacious '.rstrip() ' spacious' >>> 'mississippi'.rstrip('ipz') 'mississ'
See
removesuffix()for a method that will remove a single suffix string rather than all of a set of characters. For example:>>> 'Monty Python'.rstrip(' Python') 'M' >>> 'Monty Python'.removesuffix(' Python') 'Monty'
See also
strip().
- str.split(sep=None, maxsplit=-1)¶
Returnerar en lista med orden i strängen, med sep som avgränsningssträng. Om maxsplit anges görs högst maxsplit uppdelningar (listan kommer alltså att ha högst
maxsplit+1element). Om maxsplit inte anges eller\-1, finns det ingen begränsning av antalet uppdelningar (alla möjliga uppdelningar görs).Om sep anges, grupperas inte på varandra följande avgränsare tillsammans och anses avgränsa tomma strängar (till exempel returnerar
'1,,2'.split(',')['1', '', '2']). Argumentet sep kan bestå av flera tecken som en enda avgränsare (för att dela med flera avgränsare, användre.split()). Om en tom sträng delas med en angiven avgränsare returneras[''].Till exempel:
>>> '1,2,3'.split(',') ['1', '2', '3'] >>> '1,2,3'.split(',', maxsplit=1) ['1', '2,3'] >>> '1,2,,3,'.split(',') ['1', '2', '', '3', ''] >>> '1<>2<>3<4'.split('<>') ['1', '2', '3<4']
Om sep inte anges eller är
Noneanvänds en annan delningsalgoritm: flera på varandra följande blanksteg betraktas som en enda separator, och resultatet innehåller inga tomma strängar i början eller slutet om strängen har inledande eller avslutande blanksteg. Om en tom sträng eller en sträng som bara består av blanksteg delas upp med enNone-separator blir följaktligen resultatet[].Till exempel:
>>> '1 2 3'.split() ['1', '2', '3'] >>> '1 2 3'.split(maxsplit=1) ['1', '2 3'] >>> ' 1 2 3 '.split() ['1', '2', '3']
Om sep inte anges eller är
Noneoch maxsplit är0, beaktas endast ledande serier av på varandra följande blanksteg.Till exempel:
>>> "".split(None, 0) [] >>> " ".split(None, 0) [] >>> " foo ".split(maxsplit=0) ['foo ']
See also
join().
- str.splitlines(keepends=False)¶
Returnerar en lista över raderna i strängen, med radbrytning vid radgränser. Radbrytningar inkluderas inte i den resulterande listan om inte keepends anges och är true.
Denna metod delar på följande linjegränser. I synnerhet är gränserna en övermängd av universal newlines.
Representation
Beskrivning
\nLinje matning
\rVagnretur
R\nVagnretur + radmatning
”v” eller ”x0b
Linjetabellering
”f” eller ”x0c
Formulärmatning
x1cFilavskiljare
x1dGruppseparator
x1eSkivseparator
\x85Nästa rad (C1-kontrollkod)
\u2028Separatorlinje
\u2029Paragrafavskiljare
Förändrat i version 3.2: ”v” och ”f” läggs till i listan över linjegränser.
Till exempel:
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines() ['ab c', '', 'de fg', 'kl'] >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True) ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
Till skillnad från
split()när en avgränsningssträng sep anges, returnerar den här metoden en tom lista för den tomma strängen, och en terminal radbrytning resulterar inte i en extra rad:>>> "".splitlines() [] >>> "One line\n".splitlines() ['One line']
Som jämförelse ger
split('\n'):>>> ''.split('\n') [''] >>> 'Two lines\n'.split('\n') ['Two lines', '']
- str.startswith(prefix[, start[, end]])¶
Returnerar
Trueom strängen börjar med prefixet, annars returnerasFalse. prefix kan också vara en tupel av prefix att leta efter. Med valfri start, testa strängen som börjar vid den positionen. Med valfri end, sluta jämföra strängen vid den positionen.Till exempel:
>>> 'Python'.startswith('Py') True >>> 'a tuple of prefixes'.startswith(('at', 'a')) True >>> 'Python is amazing'.startswith('is', 7) True
See also
endswith()andremoveprefix().
- str.strip(chars=None, /)¶
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or
None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.Till exempel:
>>> ' spacious '.strip() 'spacious' >>> 'www.example.com'.strip('cmowz.') 'example'
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end.
Till exempel:
>>> comment_string = '#....... Section 3.2.1 Issue #32 .......' >>> comment_string.strip('.#! ') 'Section 3.2.1 Issue #32'
See also
rstrip().
- str.swapcase()¶
Returnerar en kopia av strängen med versaler omvandlade till gemener och vice versa. Observera att det inte nödvändigtvis är sant att
s.swapcase().swapcase() == s.
- str.title()¶
Returnerar en titelanpassad version av strängen där orden börjar med en versal och övriga tecken är gemener.
Till exempel:
>>> 'Hello world'.title() 'Hello World'
Algoritmen använder en enkel språkoberoende definition av ett ord som grupper av på varandra följande bokstäver. Definitionen fungerar i många sammanhang men innebär att apostrofer i sammandragningar och possessiver bildar ordgränser, vilket kanske inte är det önskade resultatet:
>>> "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk"
Funktionen
string.capwords()har inte detta problem, eftersom den endast delar upp ord efter mellanslag.Alternativt kan en lösning för apostrofer konstrueras med hjälp av reguljära uttryck:
>>> import re >>> def titlecase(s): ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", ... lambda mo: mo.group(0).capitalize(), ... s) ... >>> titlecase("they're bill's friends.") "They're Bill's Friends."
See also
istitle().
- str.translate(table, /)¶
Returnerar en kopia av strängen där varje tecken har mappats genom den angivna översättningstabellen. Tabellen måste vara ett objekt som implementerar indexering via
__getitem__(), vanligtvis en mapping eller sequence. När tabellen indexeras med en Unicode-ordinal (ett heltal) kan tabellobjektet göra något av följande: returnera en Unicode-ordinal eller en sträng, för att mappa tecknet till ett eller flera andra tecken; returneraNone, för att ta bort tecknet från retursträngen; eller skapa ettLookupError-undantag, för att mappa tecknet till sig själv.Du kan använda
str.maketrans()för att skapa en översättningsmappning från tecken-till-tecken-mappningar i olika format.Se även modulen
codecsför en mer flexibel metod för anpassade teckenmappningar.
- str.upper()¶
Returnerar en kopia av strängen med alla tecken med versaler [4] konverterade till versaler. Observera att
s.upper().isupper()kan varaFalseomsinnehåller obehandlade tecken eller om Unicode-kategorin för de resulterande tecknen inte är ”Lu” (Letter, uppercase), utan t.ex. ”Lt” (Letter, titlecase).Den uppercasing-algoritm som används beskrivs i avsnitt 3.13 ”Default Case Folding” i Unicode-standarden.
- str.zfill(width, /)¶
Returnerar en kopia av strängen som fyllts med ASCII
'0'siffror för att skapa en sträng med längden bredd. Ett ledande teckenprefix ('+'/'-') hanteras genom att utfyllnaden infogas efter tecknet i stället för före. Den ursprungliga strängen returneras om width är mindre än eller lika medlen(s).Till exempel:
>>> "42".zfill(5) '00042' >>> "-42".zfill(5) '-0042'
See also
rjust().
Formaterade strängbokstäver (f-strängar)¶
Added in version 3.6.
Förändrat i version 3.8: Added the debug specifier (=)
Förändrat i version 3.12: Många restriktioner för uttryck inom f-strängar har tagits bort. Bland annat är nästlade strängar, kommentarer och backslash nu tillåtna.
An f-string (formally a formatted string literal) is
a string literal that is prefixed with f or F.
This type of string literal allows embedding the results of arbitrary Python
expressions within replacement fields, which are delimited by curly
brackets ({}).
Each replacement field must contain an expression, optionally followed by:
a debug specifier – an equal sign (
=);a conversion specifier –
!s,!ror!a; and/ora format specifier prefixed with a colon (
:).
See the Lexical Analysis section on f-strings for details on the syntax of these fields.
Debug specifier¶
Added in version 3.8.
If a debug specifier – an equal sign (=) – appears after the replacement
field expression, the resulting f-string will contain the expression’s source,
the equal sign, and the value of the expression.
This is often useful for debugging:
>>> number = 14.3
>>> f'{number=}'
'number=14.3'
Whitespace before, inside and after the expression, as well as whitespace after the equal sign, is significant — it is retained in the result:
>>> f'{ number - 4 = }'
' number - 4 = 10.3'
Conversion specifier¶
By default, the value of a replacement field expression is converted to
a string using str():
>>> from fractions import Fraction
>>> one_third = Fraction(1, 3)
>>> f'{one_third}'
'1/3'
When a debug specifier but no format specifier is used, the default conversion
instead uses repr():
>>> f'{one_third = }'
'one_third = Fraction(1, 3)'
The conversion can be specified explicitly using one of these specifiers:
Till exempel:
>>> str(one_third)
'1/3'
>>> repr(one_third)
'Fraction(1, 3)'
>>> f'{one_third!s} is {one_third!r}'
'1/3 is Fraction(1, 3)'
>>> string = "¡kočka 😸!"
>>> ascii(string)
"'\\xa1ko\\u010dka \\U0001f638!'"
>>> f'{string = !a}'
"string = '\\xa1ko\\u010dka \\U0001f638!'"
Format specifier¶
After the expression has been evaluated, and possibly converted using an
explicit conversion specifier, it is formatted using the format() function.
If the replacement field includes a format specifier introduced by a colon
(:), the specifier is passed to format() as the second argument.
The result of format() is then used as the final value for the
replacement field. For example:
>>> from fractions import Fraction
>>> one_third = Fraction(1, 3)
>>> f'{one_third:.6f}'
'0.333333'
>>> f'{one_third:_^+10}'
'___+1/3___'
>>> >>> f'{one_third!r:_^20}'
'___Fraction(1, 3)___'
>>> f'{one_third = :~>10}~'
'one_third = ~~~~~~~1/3~'
Template String Literals (t-strings)¶
An t-string (formally a template string literal) is
a string literal that is prefixed with t or T.
These strings follow the same syntax and evaluation rules as formatted string literals, with for the following differences:
I stället för att utvärderas till ett
str-objekt utvärderas mallsträngkonstanter till ettstring.templatelib.Template-objekt.Protokollet
format()används inte. Istället skickas formatangivaren och konverteringar (om några) till ett nyttInterpolation-objekt som skapas för varje utvärderat uttryck. Det är upp till koden som bearbetar det resulterandeTemplate-objektet att bestämma hur formatspecifikatorer och konverteringar ska hanteras.Formatspecifikatorer som innehåller kapslade ersättningsfält utvärderas omedelbart innan de skickas till objektet
Interpolation. Till exempel kommer en interpolering av formen{amount:.{precision}f}att utvärdera det inre uttrycket{precision}för att bestämma värdet på attributetformat_spec. Omprecisionvore2, skulle det resulterande formatangivaren bli'.2f'.När likhetstecknet
'='anges i ett interpolationsuttryck, läggs uttryckets text till den bokstavliga sträng som föregår den relevanta interpolationen. Detta inkluderar likhetstecknet och eventuella omgivande blanktecken. InstansenInterpolationför uttrycket skapas som vanligt, förutom attconversionsom standard sätts till ’r’ (repr()). Om en explicit konvertering eller formatangivelse anges, åsidosätts standardbeteendet.
strängformatering i stil med printf¶
Observera
De formateringsåtgärder som beskrivs här uppvisar en rad egenheter som leder till ett antal vanliga fel (t.ex. att tupler och ordböcker inte visas korrekt).
Genom att använda formaterade strängkonstanter, gränssnittet str.format() eller string.Template kan du undvika dessa fel. Var och en av dessa alternativ har sina egna för- och nackdelar när det gäller enkelhet, flexibilitet och/eller utbyggbarhet.
Strängobjekt har en unik inbyggd operation: operatorn % (modulo). Den är också känd som strängens formatering eller interpolering-operator. Givet format % värden (där format är en sträng), ersätts % konverteringsspecifikationer i format med noll eller flera element i värden. Effekten liknar användningen av funktionen sprintf() i C-språket. Ett exempel:
>>> print('%s has %d quote types.' % ('Python', 2))
Python has 2 quote types.
Om format kräver ett enda argument kan values vara ett enda objekt som inte är en tupel. [5] Annars måste values vara en tupel med exakt det antal objekt som anges i formatsträngen, eller ett enda mappningsobjekt (t.ex. en ordbok).
En konverteringsspecifikator innehåller två eller flera tecken och har följande komponenter, som måste förekomma i denna ordning:
Tecknet
'%', som markerar början på specifikationen.Mappningsnyckel (valfri) som består av en sekvens av tecken inom parentes (t.ex.
(somename)).Konverteringsflaggor (valfritt), som påverkar resultatet av vissa konverteringstyper.
Minsta fältbredd (valfritt). Om den anges som en
'*'(asterisk) läses den faktiska bredden från nästa element i tupeln i values, och objektet som ska konverteras kommer efter den minsta fältbredden och den valfria precisionen.Precision (optional), given as a
'.'(dot) followed by the precision. If specified as'*'(an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.Length modifier (optional).
Conversion type.
When the right argument is a dictionary (or other mapping type), then the
formats in the string must include a parenthesised mapping key into that
dictionary inserted immediately after the '%' character. The mapping key
selects the value to be formatted from the mapping. For example:
>>> print('%(language)s has %(number)03d quote types.' %
... {'language': "Python", "number": 2})
Python has 002 quote types.
In this case no * specifiers may occur in a format (since they require a
sequential parameter list).
The conversion flag characters are:
Flag |
Betydelse |
|---|---|
|
The value conversion will use the ”alternate form” (where defined below). |
|
The conversion will be zero padded for numeric values. |
|
The converted value is left adjusted (overrides the |
|
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. |
|
A sign character ( |
A length modifier (h, l, or L) may be present, but is ignored as it
is not necessary for Python – so e.g. %ld is identical to %d.
The conversion types are:
Conversion |
Betydelse |
Anteckningar |
|---|---|---|
|
Signed integer decimal. |
|
|
Signed integer decimal. |
|
|
Signed octal value. |
(1) |
|
Obsolete type – it is identical to |
(6) |
|
Signed hexadecimal (lowercase). |
(2) |
|
Signed hexadecimal (uppercase). |
(2) |
|
Floating-point exponential format (lowercase). |
(3) |
|
Floating-point exponential format (uppercase). |
(3) |
|
Floating-point decimal format. |
(3) |
|
Floating-point decimal format. |
(3) |
|
Floating-point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. |
(4) |
|
Floating-point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. |
(4) |
|
Single character (accepts integer or single character string). |
|
|
String (converts any Python object using
|
(5) |
|
String (converts any Python object using
|
(5) |
|
String (converts any Python object using
|
(5) |
|
No argument is converted, results in a |
For floating-point formats, the result should be correctly rounded to a given
precision p of digits after the decimal point. The rounding mode matches
that of the round() builtin.
Anteckningar:
The alternate form causes a leading octal specifier (
'0o') to be inserted before the first digit.The alternate form causes a leading
'0x'or'0X'(depending on whether the'x'or'X'format was used) to be inserted before the first digit.The alternate form causes the result to always contain a decimal point, even if no digits follow it.
The precision determines the number of digits after the decimal point and defaults to 6.
The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.
The precision determines the number of significant digits before and after the decimal point and defaults to 6.
If precision is
N, the output is truncated toNcharacters.See PEP 237.
Since Python strings have an explicit length, %s conversions do not assume
that '\0' is the end of the string.
Förändrat i version 3.1: %f conversions for numbers whose absolute value is over 1e50 are no
longer replaced by %g conversions.
Binary Sequence Types — bytes, bytearray, memoryview¶
The core built-in types for manipulating binary data are bytes and
bytearray. They are supported by memoryview which uses
the buffer protocol to access the memory of other
binary objects without needing to make a copy.
The array module supports efficient storage of basic data types like
32-bit integers and IEEE754 double-precision floating values.
Bytes Objects¶
Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.
- class bytes(source=b'')¶
- class bytes(source, encoding, errors='strict')
Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a
bprefix is added:Single quotes:
b'still allows embedded "double" quotes'Double quotes:
b"still allows embedded 'single' quotes"Triple quoted:
b'''3 single quotes''',b"""3 double quotes"""
Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence.
As with string literals, bytes literals may also use a
rprefix to disable processing of escape sequences. See String and Bytes literals for more about the various forms of bytes literal, including supported escape sequences.While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that
0 <= x < 256(attempts to violate this restriction will triggerValueError). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).In addition to the literal forms, bytes objects can be created in a number of other ways:
A zero-filled bytes object of a specified length:
bytes(10)From an iterable of integers:
bytes(range(20))Copying existing binary data via the buffer protocol:
bytes(obj)
Also see the bytes built-in.
Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format:
- classmethod fromhex(string, /)¶
This
bytesclass method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.>>> bytes.fromhex('2Ef0 F1f2 ') b'.\xf0\xf1\xf2'
Förändrat i version 3.7:
bytes.fromhex()now skips all ASCII whitespace in the string, not just spaces.Förändrat i version 3.14:
bytes.fromhex()now accepts ASCIIbytesand bytes-like objects as input.
A reverse conversion function exists to transform a bytes object into its hexadecimal representation.
- hex(*, bytes_per_sep=1)¶
- hex(sep, bytes_per_sep=1)
Return a string object containing two hexadecimal digits for each byte in the instance.
>>> b'\xf0\xf1\xf2'.hex() 'f0f1f2'
If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default, this separator will be included between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left.
>>> value = b'\xf0\xf1\xf2' >>> value.hex('-') 'f0-f1-f2' >>> value.hex('_', 2) 'f0_f1f2' >>> b'UUDDLRLRAB'.hex(' ', -4) '55554444 4c524c52 4142'
Added in version 3.5.
Förändrat i version 3.8:
bytes.hex()now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
Since bytes objects are sequences of integers (akin to a tuple), for a bytes
object b, b[0] will be an integer, while b[0:1] will be a bytes
object of length 1. (This contrasts with text strings, where both indexing
and slicing will produce a string of length 1)
The representation of bytes objects uses the literal format (b'...')
since it is often more useful than e.g. bytes([46, 46, 46]). You can
always convert a bytes object into a list of integers using list(b).
Bytearray Objects¶
bytearray objects are a mutable counterpart to bytes
objects.
- class bytearray(source=b'')¶
- class bytearray(source, encoding, errors='strict')
There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor:
Creating an empty instance:
bytearray()Creating a zero-filled instance with a given length:
bytearray(10)From an iterable of integers:
bytearray(range(20))Copying existing binary data via the buffer protocol:
bytearray(b'Hi!')
As bytearray objects are mutable, they support the mutable sequence operations in addition to the common bytes and bytearray operations described in Bytes and Bytearray Operations.
Also see the bytearray built-in.
Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format:
- classmethod fromhex(string, /)¶
This
bytearrayclass method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.>>> bytearray.fromhex('2Ef0 F1f2 ') bytearray(b'.\xf0\xf1\xf2')
Förändrat i version 3.7:
bytearray.fromhex()now skips all ASCII whitespace in the string, not just spaces.Förändrat i version 3.14:
bytearray.fromhex()now accepts ASCIIbytesand bytes-like objects as input.
A reverse conversion function exists to transform a bytearray object into its hexadecimal representation.
- hex(*, bytes_per_sep=1)¶
- hex(sep, bytes_per_sep=1)
Return a string object containing two hexadecimal digits for each byte in the instance.
>>> bytearray(b'\xf0\xf1\xf2').hex() 'f0f1f2'
Added in version 3.5.
Förändrat i version 3.8: Similar to
bytes.hex(),bytearray.hex()now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
- resize(size, /)¶
Resize the
bytearrayto contain size bytes. size must be greater than or equal to 0.If the
bytearrayneeds to shrink, bytes beyond size are truncated.If the
bytearrayneeds to grow, all new bytes, those beyond size, will be set to null bytes.This is equivalent to:
>>> def resize(ba, size): ... if len(ba) > size: ... del ba[size:] ... else: ... ba += b'\0' * (size - len(ba))
Examples:
>>> shrink = bytearray(b'abc') >>> shrink.resize(1) >>> (shrink, len(shrink)) (bytearray(b'a'), 1) >>> grow = bytearray(b'abc') >>> grow.resize(5) >>> (grow, len(grow)) (bytearray(b'abc\x00\x00'), 5)
Added in version 3.14.
Since bytearray objects are sequences of integers (akin to a list), for a
bytearray object b, b[0] will be an integer, while b[0:1] will be
a bytearray object of length 1. (This contrasts with text strings, where
both indexing and slicing will produce a string of length 1)
The representation of bytearray objects uses the bytes literal format
(bytearray(b'...')) since it is often more useful than e.g.
bytearray([46, 46, 46]). You can always convert a bytearray object into
a list of integers using list(b).
Se även
For detailed information on thread-safety guarantees for bytearray
objects, see Thread safety for bytearray objects.
Bytes and Bytearray Operations¶
Both bytes and bytearray objects support the common sequence operations. They interoperate not just with operands of the same type, but with any bytes-like object. Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands.
Observera
The methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments. For example, you have to write:
a = "abc"
b = a.replace("a", "f")
and:
a = b"abc"
b = a.replace(b"a", b"f")
Some bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below.
Observera
Using these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption.
The following methods on bytes and bytearray objects can be used with arbitrary binary data.
- bytes.count(sub[, start[, end]])¶
- bytearray.count(sub[, start[, end]])¶
Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
If sub is empty, returns the number of empty slices between characters which is the length of the bytes object plus one.
Förändrat i version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
- bytes.removeprefix(prefix, /)¶
- bytearray.removeprefix(prefix, /)¶
If the binary data starts with the prefix string, return
bytes[len(prefix):]. Otherwise, return a copy of the original binary data:>>> b'TestHook'.removeprefix(b'Test') b'Hook' >>> b'BaseTestCase'.removeprefix(b'Test') b'BaseTestCase'
The prefix may be any bytes-like object.
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
Added in version 3.9.
- bytes.removesuffix(suffix, /)¶
- bytearray.removesuffix(suffix, /)¶
If the binary data ends with the suffix string and that suffix is not empty, return
bytes[:-len(suffix)]. Otherwise, return a copy of the original binary data:>>> b'MiscTests'.removesuffix(b'Tests') b'Misc' >>> b'TmpDirMixin'.removesuffix(b'Tests') b'TmpDirMixin'
The suffix may be any bytes-like object.
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
Added in version 3.9.
- bytes.decode(encoding='utf-8', errors='strict')¶
- bytearray.decode(encoding='utf-8', errors='strict')¶
Return the bytes decoded to a
str.encoding är som standard
'utf-8'; se Standard Encodings för möjliga värden.errors controls how decoding errors are handled. If
'strict'(the default), aUnicodeErrorexception is raised. Other possible values are'ignore','replace', and any other name registered viacodecs.register_error(). See Error Handlers for details.For performance reasons, the value of errors is not checked for validity unless a decoding error actually occurs, Python Development Mode is enabled or a debug build is used.
Observera
Passing the encoding argument to
strallows decoding any bytes-like object directly, without needing to make a temporarybytesorbytearrayobject.Förändrat i version 3.1: Stöd för nyckelordsargument har lagts till.
Förändrat i version 3.9: Värdet på errors-argumentet kontrolleras nu i Python Development Mode och i debug mode.
- bytes.endswith(suffix[, start[, end]])¶
- bytearray.endswith(suffix[, start[, end]])¶
Return
Trueif the binary data ends with the specified suffix, otherwise returnFalse. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.The suffix(es) to search for may be any bytes-like object.
- bytes.find(sub[, start[, end]])¶
- bytearray.find(sub[, start[, end]])¶
Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice
s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return-1if sub is not found.The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Observera
The
find()method should be used only if you need to know the position of sub. To check if sub is a substring or not, use theinoperator:>>> b'Py' in b'Python' True
Förändrat i version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
- bytes.index(sub[, start[, end]])¶
- bytearray.index(sub[, start[, end]])¶
Like
find(), but raiseValueErrorwhen the subsequence is not found.The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Förändrat i version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
- bytes.join(iterable, /)¶
- bytearray.join(iterable, /)¶
Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A
TypeErrorwill be raised if there are any values in iterable that are not bytes-like objects, includingstrobjects. The separator between elements is the contents of the bytes or bytearray object providing this method.
- static bytes.maketrans(from, to, /)¶
- static bytearray.maketrans(from, to, /)¶
This static method returns a translation table usable for
bytes.translate()that will map each character in from into the character at the same position in to; from and to must both be bytes-like objects and have the same length.Added in version 3.1.
- bytes.partition(sep, /)¶
- bytearray.partition(sep, /)¶
Split the sequence at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects.
The separator to search for may be any bytes-like object.
- bytes.replace(old, new, count=-1, /)¶
- bytearray.replace(old, new, count=-1, /)¶
Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
The subsequence to search for and its replacement may be any bytes-like object.
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.rfind(sub[, start[, end]])¶
- bytearray.rfind(sub[, start[, end]])¶
Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within
s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return-1on failure.The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Förändrat i version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
- bytes.rindex(sub[, start[, end]])¶
- bytearray.rindex(sub[, start[, end]])¶
Like
rfind()but raisesValueErrorwhen the subsequence sub is not found.The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.
Förändrat i version 3.3: Also accept an integer in the range 0 to 255 as the subsequence.
- bytes.rpartition(sep, /)¶
- bytearray.rpartition(sep, /)¶
Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence.
The separator to search for may be any bytes-like object.
- bytes.startswith(prefix[, start[, end]])¶
- bytearray.startswith(prefix[, start[, end]])¶
Returnerar
Trueom de binära data börjar med det angivna prefixet, annars returnerasFalse. prefix kan också vara en tupel av prefix att leta efter. Med valfri start börjar testet vid den positionen. Med valfri end, sluta jämföra vid den positionen.Prefixet/prefixen att söka efter kan vara valfri bytesliknande objekt.
- bytes.translate(table, /, delete=b'')¶
- bytearray.translate(table, /, delete=b'')¶
Returnerar en kopia av bytes- eller bytearray-objektet där alla bytes som förekommer i det valfria argumentet delete har tagits bort, och de återstående bytesen har mappats genom den angivna översättningstabellen, som måste vara ett bytes-objekt med längden 256.
Du kan använda metoden
bytes.maketrans()för att skapa en översättningstabell.Sätt argumentet table till
Noneför översättningar som bara tar bort tecken:>>> b'read this short text'.translate(None, b'aeiou') b'rd ths shrt txt'
Förändrat i version 3.6: delete stöds nu som ett nyckelordsargument.
Följande metoder för bytes och bytearray-objekt har standardbeteenden som förutsätter användning av ASCII-kompatibla binära format, men kan ändå användas med godtyckliga binära data genom att lämpliga argument anges. Observera att alla bytearray-metoder i det här avsnittet inte fungerar på plats, utan istället producerar nya objekt.
- bytes.center(width, fillbyte=b' ', /)¶
- bytearray.center(width, fillbyte=b' ', /)¶
Returnerar en kopia av objektet centrerat i en sekvens med längden width. Utfyllnad görs med hjälp av den angivna fillbyte (standard är ett ASCII-utrymme). För
bytes-objekt returneras originalsekvensen om width är mindre än eller lika medlen(s).Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.ljust(width, fillbyte=b' ', /)¶
- bytearray.ljust(width, fillbyte=b' ', /)¶
Returnerar en kopia av objektet vänsterjusterat i en sekvens med längden bredd. Utfyllnad görs med hjälp av den angivna fillbyte (standard är ett ASCII-utrymme). För
bytes-objekt returneras originalsekvensen om width är mindre än eller lika medlen(s).Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.lstrip(bytes=None, /)¶
- bytearray.lstrip(bytes=None, /)¶
Returnera en kopia av sekvensen med angivna inledande byte borttagna. Argumentet bytes är en binär sekvens som anger uppsättningen bytevärden som ska tas bort. Om det utelämnas eller är
None, tas ASCII-mellanslag bort som standard. Argumentet bytes är inte ett prefix; istället tas alla kombinationer av dess värden bort:>>> b' spacious '.lstrip() b'spacious ' >>> b'www.example.com'.lstrip(b'cmowz.') b'example.com'
Den binära sekvensen av bytevärden som ska tas bort kan vara valfri bytesliknande objekt. Se
removeprefix()för en metod som tar bort en enda prefixsträng i stället för alla tecken i en uppsättning. Till exempel:>>> b'Arthur: three!'.lstrip(b'Arthur: ') b'ee!' >>> b'Arthur: three!'.removeprefix(b'Arthur: ') b'three!'
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.rjust(width, fillbyte=b' ', /)¶
- bytearray.rjust(width, fillbyte=b' ', /)¶
Returnerar en kopia av objektet högerställd i en sekvens med längd bredd. Utfyllnad görs med hjälp av den angivna fillbyte (standard är ett ASCII-utrymme). För
bytes-objekt returneras originalsekvensen om width är mindre än eller lika medlen(s).Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.rsplit(sep=None, maxsplit=-1)¶
- bytearray.rsplit(sep=None, maxsplit=-1)¶
Dela upp den binära sekvensen i undersekvenser av samma typ, med sep som avgränsningssträng. Om maxsplit anges görs högst maxsplit uppdelningar, de högst till höger. Om sep inte specificeras eller om
None, är varje delsekvens som enbart består av ASCII-teckensnitt en separator. Förutom att dela upp från höger, beter sigrsplit()somsplit()som beskrivs i detalj nedan.
- bytes.rstrip(bytes=None, /)¶
- bytearray.rstrip(bytes=None, /)¶
Returnera en kopia av sekvensen med angivna efterföljande byte borttagna. Argumentet bytes är en binär sekvens som anger uppsättningen bytevärden som ska tas bort. Om det utelämnas eller är
None, tas ASCII-mellanslag bort som standard. Argumentet bytes är inte ett suffix; istället tas alla kombinationer av dess värden bort:>>> b' spacious '.rstrip() b' spacious' >>> b'mississippi'.rstrip(b'ipz') b'mississ'
Den binära sekvensen av bytevärden som ska tas bort kan vara valfritt bytesliknande objekt. Se
removesuffix()för en metod som tar bort en enda suffixsträng i stället för alla tecken i en uppsättning. Till exempel:>>> b'Monty Python'.rstrip(b' Python') b'M' >>> b'Monty Python'.removesuffix(b' Python') b'Monty'
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.split(sep=None, maxsplit=-1)¶
- bytearray.split(sep=None, maxsplit=-1)¶
Dela upp den binära sekvensen i undersekvenser av samma typ, med sep som avgränsningssträng. Om maxsplit anges och är icke-negativ görs högst maxsplit uppdelningar (listan kommer alltså att ha högst
maxsplit+1element). Om maxsplit inte anges eller är\-1finns det ingen begränsning av antalet uppdelningar (alla möjliga uppdelningar görs).Om sep anges grupperas inte på varandra följande avgränsare och de anses avgränsa tomma undersekvenser (t.ex.
b'1,,2'.split(b',')ger[b'1', b'', b'2']). Argumentet sep kan bestå av en multibyte-sekvens som en enda avgränsare. Om en tom sekvens delas med en angiven separator returneras[b'']eller[bytearray(b'')]beroende på vilken typ av objekt som delas. Argumentet sep kan vara valfri bytesliknande objekt.Till exempel:
>>> b'1,2,3'.split(b',') [b'1', b'2', b'3'] >>> b'1,2,3'.split(b',', maxsplit=1) [b'1', b'2,3'] >>> b'1,2,,3,'.split(b',') [b'1', b'2', b'', b'3', b''] >>> b'1<>2<>3<4'.split(b'<>') [b'1', b'2', b'3<4']
Om sep inte anges eller är
None, används en annan delningsalgoritm: sekvenser av på varandra följande ASCII-teckensnitt betraktas som en enda separator, och resultatet innehåller inga tomma strängar i början eller slutet om sekvensen har inledande eller avslutande teckensnitt. Följaktligen returneras[]när en tom sekvens eller en sekvens som endast består av ASCII-teckensnitt utan en angiven separator delas.Till exempel:
>>> b'1 2 3'.split() [b'1', b'2', b'3'] >>> b'1 2 3'.split(maxsplit=1) [b'1', b'2 3'] >>> b' 1 2 3 '.split() [b'1', b'2', b'3']
- bytes.strip(bytes=None, /)¶
- bytearray.strip(bytes=None, /)¶
Returnera en kopia av sekvensen med angivna inledande och avslutande byte borttagna. Argumentet bytes är en binär sekvens som anger den uppsättning bytevärden som ska tas bort. Om det utelämnas eller är
None, tas ASCII-mellanslag bort som standard. Argumentet bytes är inte ett prefix eller suffix; istället tas alla kombinationer av dess värden bort:>>> b' spacious '.strip() b'spacious' >>> b'www.example.com'.strip(b'cmowz.') b'example'
Den binära sekvensen av bytevärden som skall tas bort kan vara valfri bytesliknande objekt.
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
Följande metoder för bytes och bytearray-objekt förutsätter användning av ASCII-kompatibla binära format och bör inte tillämpas på godtyckliga binära data. Observera att alla bytearray-metoder i detta avsnitt inte arbetar på plats, utan istället producerar nya objekt.
- bytes.capitalize()¶
- bytearray.capitalize()¶
Returnerar en kopia av sekvensen där varje byte tolkas som ett ASCII-tecken och den första byten skrivs med stor bokstav och resten med liten bokstav. Bytevärden som inte är ASCII-värden skickas oförändrade.
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.expandtabs(tabsize=8)¶
- bytearray.expandtabs(tabsize=8)¶
Returnerar en kopia av sekvensen där alla ASCII tabbtecken ersätts av ett eller flera ASCII-rymder, beroende på aktuell kolumn och angiven tabbstorlek. Tabbpositioner förekommer varje tabsize byte (standard är 8, vilket ger tabbpositioner i kolumnerna 0, 8, 16 och så vidare). För att expandera sekvensen sätts den aktuella kolumnen till noll och sekvensen undersöks byte för byte. Om byten är ett ASCII-tab-tecken (
b'\t') infogas ett eller flera mellanslagstecken i resultatet tills den aktuella kolumnen är lika med nästa tab-position. (Tabbtecknet i sig kopieras inte.) Om den aktuella byten är en ASCII newline (b'\n') eller carriage return (b'\r') kopieras den och den aktuella kolumnen nollställs. Alla andra bytevärden kopieras oförändrade och den aktuella kolumnen ökas med ett oavsett hur bytevärdet representeras när det skrivs ut:>>> b'01\t012\t0123\t01234'.expandtabs() b'01 012 0123 01234' >>> b'01\t012\t0123\t01234'.expandtabs(4) b'01 012 0123 01234'
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.isalnum()¶
- bytearray.isalnum()¶
Returnerar
Trueom alla bytes i sekvensen är alfabetiska ASCII-tecken eller ASCIIdecimalsiffror och sekvensen inte är tom, annarsFalse. Alfabetiska ASCII-tecken är de bytevärden som finns i sekvensenb'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. ASCII decimalsiffror är de bytevärden i sekvensenb'0123456789'.Till exempel:
>>> b'ABCabc1'.isalnum() True >>> b'ABC abc1'.isalnum() False
- bytes.isalpha()¶
- bytearray.isalpha()¶
Returnerar
Trueom alla bytes i sekvensen är alfabetiska ASCII-tecken och sekvensen inte är tom, annarsFalse. Alfabetiska ASCII-tecken är de bytevärden som finns i sekvensenb'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.Till exempel:
>>> b'ABCabc'.isalpha() True >>> b'ABCabc1'.isalpha() False
- bytes.isascii()¶
- bytearray.isascii()¶
Returnerar
Trueom sekvensen är tom eller om alla byte i sekvensen är ASCII, annarsFalse. ASCII-bytes ligger i intervallet 0-0x7F.Added in version 3.7.
- bytes.isdigit()¶
- bytearray.isdigit()¶
Returnerar
Trueom alla bytes i sekvensen är ASCII decimala siffror och sekvensen inte är tom, annarsFalse. ASCII decimalsiffror är de bytevärden som finns i sekvensenb'0123456789'.Till exempel:
>>> b'1234'.isdigit() True >>> b'1.23'.isdigit() False
- bytes.islower()¶
- bytearray.islower()¶
Returnerar
Trueom det finns minst ett ASCII-tecken med små bokstäver i sekvensen och inga ASCII-tecken med stora bokstäver, annarsFalse.Till exempel:
>>> b'hello world'.islower() True >>> b'Hello world'.islower() False
ASCII-tecken med gemener är de bytevärden som ingår i sekvensen
b'abcdefghijklmnopqrstuvwxyz'. Versala ASCII-tecken är de bytevärden som ingår i sekvensenb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
- bytes.isspace()¶
- bytearray.isspace()¶
Returnerar
Trueom alla byte i sekvensen är ASCII blanksteg och sekvensen inte är tom, annarsFalse. ASCII-tecknen för blanksteg är de bytevärden i sekvensenb' \t\n\r\x0b\f'(mellanslag, tabb, ny rad, vagnsretur, vertikal tabb, form feed).
- bytes.istitle()¶
- bytearray.istitle()¶
Returnerar
Trueom sekvensen är ASCII titlecase och sekvensen inte är tom,Falseannars. Sebytes.title()för mer information om definitionen av ”titlecase”.Till exempel:
>>> b'Hello World'.istitle() True >>> b'Hello world'.istitle() False
- bytes.isupper()¶
- bytearray.isupper()¶
Returnerar
Trueom det finns minst ett versalt alfabetiskt ASCII-tecken i sekvensen och inga gemena ASCII-tecken, annarsFalse.Till exempel:
>>> b'HELLO WORLD'.isupper() True >>> b'Hello world'.isupper() False
ASCII-tecken med gemener är de bytevärden som ingår i sekvensen
b'abcdefghijklmnopqrstuvwxyz'. Versala ASCII-tecken är de bytevärden som ingår i sekvensenb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
- bytes.lower()¶
- bytearray.lower()¶
Returnerar en kopia av sekvensen med alla ASCII-tecken med versaler konverterade till motsvarande tecken med gemener.
Till exempel:
>>> b'Hello World'.lower() b'hello world'
ASCII-tecken med gemener är de bytevärden som ingår i sekvensen
b'abcdefghijklmnopqrstuvwxyz'. Versala ASCII-tecken är de bytevärden som ingår i sekvensenb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.splitlines(keepends=False)¶
- bytearray.splitlines(keepends=False)¶
Returnerar en lista med raderna i den binära sekvensen, med brytning vid ASCII-radgränser. Den här metoden använder universal newlines för att dela upp rader. Radbrytningar inkluderas inte i den resulterande listan om inte keepends anges och är true.
Till exempel:
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines() [b'ab c', b'', b'de fg', b'kl'] >>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True) [b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
Till skillnad från
split()när en avgränsningssträng sep anges, returnerar den här metoden en tom lista för den tomma strängen, och en terminal radbrytning resulterar inte i en extra rad:>>> b"".split(b'\n'), b"Two lines\n".split(b'\n') ([b''], [b'Two lines', b'']) >>> b"".splitlines(), b"One line\n".splitlines() ([], [b'One line'])
- bytes.swapcase()¶
- bytearray.swapcase()¶
Returnerar en kopia av sekvensen med alla ASCII-tecken med gemener konverterade till motsvarande tecken med versaler och vice versa.
Till exempel:
>>> b'Hello World'.swapcase() b'hELLO wORLD'
ASCII-tecken med gemener är de bytevärden som ingår i sekvensen
b'abcdefghijklmnopqrstuvwxyz'. Versala ASCII-tecken är de bytevärden som ingår i sekvensenb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.Till skillnad från
str.swapcase()är det alltid så attbin.swapcase().swapcase() == binför de binära versionerna. Omvandling av versaler är symmetrisk i ASCII, även om det i allmänhet inte är sant för godtyckliga Unicode-kodpunkter.Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.title()¶
- bytearray.title()¶
Returnerar en version med versaler av den binära sekvensen där orden börjar med ett ASCII-tecken med versaler och de återstående tecknen är gemener. Bytevärden som inte är versaler lämnas oförändrade.
Till exempel:
>>> b'Hello world'.title() b'Hello World'
ASCII-tecken med gemener är de bytevärden som ingår i sekvensen
b'abcdefghijklmnopqrstuvwxyz'. Versala ASCII-tecken är de bytevärden i sekvensenb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. Alla andra bytevärden är okommaterade.Algoritmen använder en enkel språkoberoende definition av ett ord som grupper av på varandra följande bokstäver. Definitionen fungerar i många sammanhang men innebär att apostrofer i sammandragningar och possessiver bildar ordgränser, vilket kanske inte är det önskade resultatet:
>>> b"they're bill's friends from the UK".title() b"They'Re Bill'S Friends From The Uk"
En lösning för apostrofer kan konstrueras med hjälp av reguljära uttryck:
>>> import re >>> def titlecase(s): ... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?", ... lambda mo: mo.group(0)[0:1].upper() + ... mo.group(0)[1:].lower(), ... s) ... >>> titlecase(b"they're bill's friends.") b"They're Bill's Friends."
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.upper()¶
- bytearray.upper()¶
Returnerar en kopia av sekvensen med alla ASCII-tecken med gemener konverterade till motsvarande tecken med versaler.
Till exempel:
>>> b'Hello World'.upper() b'HELLO WORLD'
ASCII-tecken med gemener är de bytevärden som ingår i sekvensen
b'abcdefghijklmnopqrstuvwxyz'. Versala ASCII-tecken är de bytevärden som ingår i sekvensenb'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
- bytes.zfill(width, /)¶
- bytearray.zfill(width, /)¶
Returnerar en kopia av den sekvens som lämnats fylld med ASCII
b'0'siffror för att skapa en sekvens med längden bredd. Ett ledande teckenprefix (b'+'/b'-') hanteras genom att utfyllnaden infogas efter tecknet istället för före. Förbytes-objekt returneras den ursprungliga sekvensen om width är mindre än eller lika medlen(seq).Till exempel:
>>> b"42".zfill(5) b'00042' >>> b"-42".zfill(5) b'-0042'
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
byteformatering i stil med printf¶
Observera
De formateringsoperationer som beskrivs här uppvisar en rad olika egenheter som leder till ett antal vanliga fel (t.ex. att tuplar och ordböcker inte visas korrekt). Om det värde som skrivs ut kan vara en tupel eller en ordbok ska det paketeras i en tupel.
Bytes-objekt (bytes/bytearray) har en unik inbyggd operation: operatorn % (modulo). Denna kallas även bytes formaterings- eller interpolationsoperatorn. Givet format % values (där format är ett bytes-objekt) ersätts % konverteringsspecifikationerna i format med noll eller flera element av values. Effekten är liknande den som uppnås med sprintf() i språket C.
Om format kräver ett enda argument kan values vara ett enda objekt som inte är en tupel. [5] Annars måste values vara en tupel med exakt det antal objekt som anges av formatbytesobjektet, eller ett enda mappningsobjekt (t.ex. en ordbok).
En konverteringsspecifikator innehåller två eller flera tecken och har följande komponenter, som måste förekomma i denna ordning:
Tecknet
'%', som markerar början på specifikationen.Mappningsnyckel (valfri) som består av en sekvens av tecken inom parentes (t.ex.
(somename)).Konverteringsflaggor (valfritt), som påverkar resultatet av vissa konverteringstyper.
Minsta fältbredd (valfritt). Om den anges som en
'*'(asterisk) läses den faktiska bredden från nästa element i tupeln i values, och objektet som ska konverteras kommer efter den minsta fältbredden och den valfria precisionen.Precision (optional), given as a
'.'(dot) followed by the precision. If specified as'*'(an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.Length modifier (optional).
Conversion type.
När det högra argumentet är en ordbok (eller annan mappningstyp), måste formaten i bytesobjektet inkludera en parentetisk mappningsnyckel till ordboken som infogas omedelbart efter tecknet '%'. Mappningsnyckeln väljer det värde som ska formateras från mappningen. Exempelvis
>>> print(b'%(language)s has %(number)03d quote types.' %
... {b'language': b"Python", b"number": 2})
b'Python has 002 quote types.'
In this case no * specifiers may occur in a format (since they require a
sequential parameter list).
The conversion flag characters are:
Flag |
Betydelse |
|---|---|
|
The value conversion will use the ”alternate form” (where defined below). |
|
The conversion will be zero padded for numeric values. |
|
The converted value is left adjusted (overrides the |
|
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. |
|
A sign character ( |
A length modifier (h, l, or L) may be present, but is ignored as it
is not necessary for Python – so e.g. %ld is identical to %d.
The conversion types are:
Conversion |
Betydelse |
Anteckningar |
|---|---|---|
|
Signed integer decimal. |
|
|
Signed integer decimal. |
|
|
Signed octal value. |
(1) |
|
Obsolete type – it is identical to |
(8) |
|
Signed hexadecimal (lowercase). |
(2) |
|
Signed hexadecimal (uppercase). |
(2) |
|
Floating-point exponential format (lowercase). |
(3) |
|
Floating-point exponential format (uppercase). |
(3) |
|
Floating-point decimal format. |
(3) |
|
Floating-point decimal format. |
(3) |
|
Floating-point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. |
(4) |
|
Floating-point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. |
(4) |
|
Single byte (accepterar objekt med heltal eller single byte). |
|
|
Bytes (alla objekt som följer buffer protocol eller har |
(5) |
|
|
(6) |
|
Bytes (konverterar valfritt Python-objekt med |
(5) |
|
|
(7) |
|
No argument is converted, results in a |
Anteckningar:
The alternate form causes a leading octal specifier (
'0o') to be inserted before the first digit.The alternate form causes a leading
'0x'or'0X'(depending on whether the'x'or'X'format was used) to be inserted before the first digit.The alternate form causes the result to always contain a decimal point, even if no digits follow it.
The precision determines the number of digits after the decimal point and defaults to 6.
The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.
The precision determines the number of significant digits before and after the decimal point and defaults to 6.
If precision is
N, the output is truncated toNcharacters.b'%s'är föråldrad, men kommer inte att tas bort under 3.x-serien.b'%r'är föråldrad, men kommer inte att tas bort under 3.x-serien.See PEP 237.
Observera
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.
Se även
PEP 461 - Lägga till % formatering till bytes och bytearray
Added in version 3.5.
Minnesvy¶
memoryview-objekt gör det möjligt för Python-kod att komma åt interna data i ett objekt som stöder buffer protocol utan kopiering.
- class memoryview(object)¶
Skapa en
memoryviewsom refererar till object. object måste stödja buffertprotokollet. Inbyggda objekt som stöder buffertprotokollet inkluderarbytesochbytearray.En
memoryviewhar begreppet element, som är den atomära minnesenhet som hanteras av det ursprungliga objektet. För många enkla typer sombytesochbytearrayär ett element en enda byte, men andra typer somarray.arraykan ha större element.len(view)är lika med längden påtolist, som är den nästlade listrepresentationen av vyn. Omview.ndim = 1är detta lika med antalet element i vyn.Förändrat i version 3.12: Om
view.ndim == 0,len(view)ger nuTypeErroristället för att returnera 1.Attributet
itemsizeger dig antalet byte i ett enda element.En
memoryviewstöder skivning och indexering för att exponera sina data. Endimensionell skivning kommer att resultera i en undervy:>>> v = memoryview(b'abcefg') >>> v[1] 98 >>> v[-1] 103 >>> v[1:4] <memory at 0x7f3ddc9f4350> >>> bytes(v[1:4]) b'bce'
Om
formatär en av de ursprungliga formatspecifikationerna från modulenstructstöds även indexering med ett heltal eller en tupel av heltal och returnerar ett enda element med rätt typ. Endimensionella minnesvyer kan indexeras med ett heltal eller en tupel med ett heltal. Flerdimensionella minnesvyer kan indexeras med tupler av exakt ndim heltal där ndim är antalet dimensioner. Nolldimensionella minnesvyer kan indexeras med den tomma tupeln.Här är ett exempel med ett format som inte är byte:
>>> import array >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444]) >>> m = memoryview(a) >>> m[0] -11111111 >>> m[-1] 44444444 >>> m[::2].tolist() [-11111111, -33333333]
Om det underliggande objektet är skrivbart stöder minnesvyn endimensionell tilldelning av skivor. Storleksändring är inte tillåtet:
>>> data = bytearray(b'abcefg') >>> v = memoryview(data) >>> v.readonly False >>> v[0] = ord(b'z') >>> data bytearray(b'zbcefg') >>> v[1:4] = b'123' >>> data bytearray(b'z123fg') >>> v[2:3] = b'spam' Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: memoryview assignment: lvalue and rvalue have different structures >>> v[2:6] = b'spam' >>> data bytearray(b'z1spam')
Endimensionella minnesvyer av hashable (skrivskyddade) typer med formaten ’B’, ’b’ eller ’c’ är också hashbara. Hash definieras som
hash(m) == hash(m.tobytes()):>>> v = memoryview(b'abcefg') >>> hash(v) == hash(b'abcefg') True >>> hash(v[2:4]) == hash(b'ce') True >>> hash(v[::-2]) == hash(b'abcefg'[::-2]) True
Förändrat i version 3.3: Endimensionella minnesvyer kan nu skivas. Endimensionella minnesvyer med formaten ’B’, ’b’ eller ’c’ är nu hashable.
Förändrat i version 3.4: memoryview registreras nu automatiskt med
collections.abc.SequenceFörändrat i version 3.5: minnesvyer kan nu indexeras med tupel av heltal.
Förändrat i version 3.14: memoryview är nu en generic type.
memoryviewhar flera metoder:- __eq__(exporter)¶
En minnesvy och en PEP 3118 exportör är lika om deras former är likvärdiga och om alla motsvarande värden är lika när operandernas respektive formatkoder tolkas med
structsyntax.För den delmängd av
structformatsträngar som för närvarande stöds avtolist(), ärvochwlika omv.tolist() == w.tolist():>>> import array >>> a = array.array('I', [1, 2, 3, 4, 5]) >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0]) >>> c = array.array('b', [5, 3, 1]) >>> x = memoryview(a) >>> y = memoryview(b) >>> x == a == y == b True >>> x.tolist() == a.tolist() == y.tolist() == b.tolist() True >>> z = y[::-2] >>> z == c True >>> z.tolist() == c.tolist() True
Om någon av formatsträngarna inte stöds av modulen
struct, kommer objekten alltid att jämföras som olika (även om formatsträngarna och buffertinnehållet är identiska):>>> from ctypes import BigEndianStructure, c_long >>> class BEPoint(BigEndianStructure): ... _fields_ = [("x", c_long), ("y", c_long)] ... >>> point = BEPoint(100, 200) >>> a = memoryview(point) >>> b = memoryview(point) >>> a == point False >>> a == b False
Observera att, precis som med flyttal,
v är winte innebärv == wför memoryview-objekt.Förändrat i version 3.3: Tidigare versioner jämförde råminnet utan att ta hänsyn till objektformatet och den logiska arraystrukturen.
- tobytes(order='C')¶
Returnerar data i bufferten som en bytestring. Detta är likvärdigt med att anropa
bytes-konstruktören på minnesvyn.>>> m = memoryview(b"abc") >>> m.tobytes() b'abc' >>> bytes(m) b'abc'
För icke sammanhängande matriser är resultatet lika med den tillplattade listrepresentationen med alla element konverterade till bytes.
tobytes()stöder alla formatsträngar, inklusive de som inte är istruct-modulsyntax.Added in version 3.8: order kan vara {’C’, ’F’, ’A’}. När order är ’C’ eller ’F’ konverteras data från den ursprungliga matrisen till C- eller Fortran-ordning. För sammanhängande vyer returnerar ’A’ en exakt kopia av det fysiska minnet. I synnerhet bevaras Fortran-ordningen i minnet. För icke-slutna vyer konverteras data först till C. order=None är samma sak som order=’C’.
- hex(*, bytes_per_sep=1)¶
- hex(sep, bytes_per_sep=1)
Returnerar ett strängobjekt som innehåller två hexadecimala siffror för varje byte i bufferten.
>>> m = memoryview(b"abc") >>> m.hex() '616263'
Added in version 3.5.
Förändrat i version 3.8: I likhet med
bytes.hex()harmemoryview.hex()nu stöd för de valfria parametrarna sep och bytes_per_sep för att infoga separatorer mellan byte i hex-utdata.
- tolist()¶
Returnera data i bufferten som en lista med element.
>>> memoryview(b'abc').tolist() [97, 98, 99] >>> import array >>> a = array.array('d', [1.1, 2.2, 3.3]) >>> m = memoryview(a) >>> m.tolist() [1.1, 2.2, 3.3]
- toreadonly()¶
Returnerar en skrivskyddad version av memoryview-objektet. Det ursprungliga memoryview-objektet är oförändrat.
>>> m = memoryview(bytearray(b'abc')) >>> mm = m.toreadonly() >>> mm.tolist() [97, 98, 99] >>> mm[0] = 42 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot modify read-only memory >>> m[0] = 43 >>> mm.tolist() [43, 98, 99]
Added in version 3.8.
- release()¶
Frigör den underliggande bufferten som exponeras av memoryview-objektet. Många objekt vidtar speciella åtgärder när en vy hålls på dem (t.ex. skulle en
bytearraytillfälligt förbjuda storleksändring); därför är det praktiskt att anropa release() för att ta bort dessa begränsningar (och frigöra eventuella hängande resurser) så snart som möjligt.Efter att denna metod har anropats ger alla ytterligare åtgärder på vyn upphov till ett
ValueError(utomrelease()själv som kan anropas flera gånger):>>> m = memoryview(b'abc') >>> m.release() >>> m[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operation forbidden on released memoryview object
Protokollet för kontexthantering kan användas för en liknande effekt med hjälp av
with-satsen:>>> with memoryview(b'abc') as m: ... m[0] ... 97 >>> m[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operation forbidden on released memoryview object
Added in version 3.2.
- cast(format, /)¶
- cast(format, shape, /)
Castar en minnesvy till ett nytt format eller en ny form. shape är som standard
[byte_length//new_itemsize], vilket innebär att resultatvyn kommer att vara endimensionell. Returvärdet är en ny minnesvy, men själva bufferten kopieras inte. Stödda casts är 1D -> C-contiguous och C-contiguous -> 1D.Målformatet är begränsat till ett inbyggt format med ett enda element i
struct-syntax. Ett av formaten måste vara ett byteformat (’B’, ’b’ eller ’c’). Byte-längden på resultatet måste vara samma som den ursprungliga längden. Observera att alla byte-längder kan bero på operativsystemet.Cast 1D/lång till 1D/unsigned bytes:
>>> import array >>> a = array.array('l', [1,2,3]) >>> x = memoryview(a) >>> x.format 'l' >>> x.itemsize 8 >>> len(x) 3 >>> x.nbytes 24 >>> y = x.cast('B') >>> y.format 'B' >>> y.itemsize 1 >>> len(y) 24 >>> y.nbytes 24
Casta 1D/unsigned bytes till 1D/char:
>>> b = bytearray(b'zyz') >>> x = memoryview(b) >>> x[0] = b'a' Traceback (most recent call last): ... TypeError: memoryview: invalid type for format 'B' >>> y = x.cast('c') >>> y[0] = b'a' >>> b bytearray(b'ayz')
Cast 1D/bytes till 3D/ints till 1D/signed char:
>>> import struct >>> buf = struct.pack("i"*12, *list(range(12))) >>> x = memoryview(buf) >>> y = x.cast('i', shape=[2,2,3]) >>> y.tolist() [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] >>> y.format 'i' >>> y.itemsize 4 >>> len(y) 2 >>> y.nbytes 48 >>> z = y.cast('b') >>> z.format 'b' >>> z.itemsize 1 >>> len(z) 48 >>> z.nbytes 48
Cast 1D/unsigned long till 2D/unsigned long:
>>> buf = struct.pack("L"*6, *list(range(6))) >>> x = memoryview(buf) >>> y = x.cast('L', shape=[2,3]) >>> len(y) 2 >>> y.nbytes 48 >>> y.tolist() [[0, 1, 2], [3, 4, 5]]
Added in version 3.3.
Förändrat i version 3.5: Källformatet är inte längre begränsat vid casting till en bytevy.
- count(value, /)¶
Räkna antalet förekomster av värde.
Added in version 3.14.
- index(value, start=0, stop=sys.maxsize, /)¶
Returnerar index för den första förekomsten av värde (vid eller efter index start och före index stop).
Utlöser ett
ValueErrorom värde inte kan hittas.Added in version 3.14.
Det finns också flera skrivskyddade attribut tillgängliga:
- obj¶
Det underliggande objektet för minnesvyn:
>>> b = bytearray(b'xyz') >>> m = memoryview(b) >>> m.obj is b True
Added in version 3.3.
- nbytes¶
nbytes == product(shape) * itemsize == len(m.tobytes()). Detta är den mängd utrymme i bytes som matrisen skulle använda i en sammanhängande representation. Det är inte nödvändigtvis lika medlen(m):>>> import array >>> a = array.array('i', [1,2,3,4,5]) >>> m = memoryview(a) >>> len(m) 5 >>> m.nbytes 20 >>> y = m[::2] >>> len(y) 3 >>> y.nbytes 12 >>> len(y.tobytes()) 12
Flerdimensionella matriser:
>>> import struct >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)]) >>> x = memoryview(buf) >>> y = x.cast('d', shape=[3,4]) >>> y.tolist() [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]] >>> len(y) 3 >>> y.nbytes 96
Added in version 3.3.
- readonly¶
En bool som anger om minnet är skrivskyddat.
- format¶
En sträng som innehåller formatet (i
struct-modulstil) för varje element i vyn. En minnesvy kan skapas från exportörer med godtyckliga formatsträngar, men vissa metoder (t.ex.tolist()) är begränsade till ursprungliga format för enstaka element.Förändrat i version 3.3: format
'B'is now handled according to the struct module syntax. This means thatmemoryview(b'abc')[0] == b'abc'[0] == 97.
- itemsize¶
The size in bytes of each element of the memoryview:
>>> import array, struct >>> m = memoryview(array.array('H', [32000, 32001, 32002])) >>> m.itemsize 2 >>> m[0] 32000 >>> struct.calcsize('H') == m.itemsize True
- ndim¶
An integer indicating how many dimensions of a multi-dimensional array the memory represents.
- shape¶
A tuple of integers the length of
ndimgiving the shape of the memory as an N-dimensional array.Förändrat i version 3.3: An empty tuple instead of
Nonewhen ndim = 0.
- strides¶
A tuple of integers the length of
ndimgiving the size in bytes to access each element for each dimension of the array.Förändrat i version 3.3: An empty tuple instead of
Nonewhen ndim = 0.
- suboffsets¶
Used internally for PIL-style arrays. The value is informational only.
- c_contiguous¶
A bool indicating whether the memory is C-contiguous.
Added in version 3.3.
- f_contiguous¶
A bool indicating whether the memory is Fortran contiguous.
Added in version 3.3.
- contiguous¶
A bool indicating whether the memory is contiguous.
Added in version 3.3.
For information on the thread safety of memoryview objects in
the free-threaded build, see Thread safety for memoryview objects.
Set Types — set, frozenset¶
A set object is an unordered collection of distinct hashable objects.
Common uses include membership testing, removing duplicates from a sequence, and
computing mathematical operations such as intersection, union, difference, and
symmetric difference.
(For other containers see the built-in dict, list,
and tuple classes, and the collections module.)
Like other collections, sets support x in set, len(set), and for x in
set. Being an unordered collection, sets do not record element position or
order of insertion. Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.
There are currently two built-in set types, set and frozenset.
The set type is mutable — the contents can be changed using methods
like add() and remove().
Since it is mutable, it has no hash value and cannot be used as
either a dictionary key or as an element of another set.
The frozenset type is immutable and hashable —
its contents cannot be altered after it is created;
it can therefore be used as a dictionary key or as an element of another set.
Non-empty sets (not frozensets) can be created by placing a comma-separated list
of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the
set constructor.
The constructors for both classes work the same:
- class set(iterable=(), /)¶
- class frozenset(iterable=(), /)¶
Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be
frozensetobjects. If iterable is not specified, a new empty set is returned.
Sets can be created by several means:
Use a comma-separated list of elements within braces:
{'jack', 'sjoerd'}Use a set comprehension:
{c for c in 'abracadabra' if c not in 'abc'}Use the type constructor:
set(),set('foobar'),set(['a', 'b', 'foo'])
Instances of set and frozenset provide the following
operations:
- len(s)
Return the number of elements in set s (cardinality of s).
- x in s
Test x for membership in s.
- x not in s
Test x for non-membership in s.
- frozenset.isdisjoint(other, /)¶
- set.isdisjoint(other, /)¶
Return
Trueif the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.
- set <= other
Test whether every element in the set is in other.
- set < other
Test whether the set is a proper subset of other, that is,
set <= other and set != other.
- set >= other
Test whether every element in other is in the set.
- set > other
Test whether the set is a proper superset of other, that is,
set >= other and set != other.
- set | other | ...
Return a new set with elements from the set and all others.
- set & other & ...
Return a new set with elements common to the set and all others.
- set - other - ...
Return a new set with elements in the set that are not in the others.
- set ^ other
Return a new set with elements in either the set or other but not both.
Note, the non-operator versions of union(),
intersection(), difference(), symmetric_difference(), issubset(), and
issuperset() methods will accept any iterable as an argument. In
contrast, their operator based counterparts require their arguments to be
sets. This precludes error-prone constructions like set('abc') & 'cbs'
in favor of the more readable set('abc').intersection('cbs').
Both set and frozenset support set to set comparisons. Two
sets are equal if and only if every element of each set is contained in the
other (each is a subset of the other). A set is less than another set if and
only if the first set is a proper subset of the second set (is a subset, but
is not equal). A set is greater than another set if and only if the first set
is a proper superset of the second set (is a superset, but is not equal).
Instances of set are compared to instances of frozenset
based on their members. For example, set('abc') == frozenset('abc')
returns True and so does set('abc') in set([frozenset('abc')]).
The subset and equality comparisons do not generalize to a total ordering
function. For example, any two nonempty disjoint sets are not equal and are not
subsets of each other, so all of the following return False: a<b,
a==b, or a>b.
Since sets only define partial ordering (subset relationships), the output of
the list.sort() method is undefined for lists of sets.
Set elements, like dictionary keys, must be hashable.
Binary operations that mix set instances with frozenset
return the type of the first operand. For example: frozenset('ab') |
set('bc') returns an instance of frozenset.
The following table lists operations available for set that do not
apply to immutable instances of frozenset:
- set.update(*others)¶
- set |= other | ...
Update the set, adding elements from all others.
- set.intersection_update(*others)¶
- set &= other & ...
Update the set, keeping only elements found in it and all others.
- set.difference_update(*others)¶
- set -= other | ...
Update the set, removing elements found in others.
- set.symmetric_difference_update(other, /)¶
- set ^= other
Update the set, keeping only elements found in either set, but not in both.
- set.add(elem, /)¶
Add element elem to the set.
- set.remove(elem, /)¶
Remove element elem from the set. Raises
KeyErrorif elem is not contained in the set.
- set.discard(elem, /)¶
Remove element elem from the set if it is present.
- set.pop()¶
Remove and return an arbitrary element from the set. Raises
KeyErrorif the set is empty.
- set.clear()¶
Remove all elements from the set.
Note, the non-operator versions of the update(),
intersection_update(), difference_update(), and
symmetric_difference_update() methods will accept any iterable as an
argument.
Note, the elem argument to the __contains__(),
remove(), and
discard() methods may be a set. To support searching for an equivalent
frozenset, a temporary one is created from elem.
Se även
For detailed information on thread-safety guarantees for set
objects, see Thread safety for set objects.
Mapping Types — dict¶
A mapping object maps hashable values to arbitrary objects.
Mappings are mutable objects. There is currently only one standard mapping
type, the dictionary. (For other containers see the built-in
list, set, and tuple classes, and the
collections module.)
A dictionary’s keys are almost arbitrary values. Values that are not
hashable, that is, values containing lists, dictionaries or other
mutable types (that are compared by value rather than by object identity) may
not be used as keys.
Values that compare equal (such as 1, 1.0, and True)
can be used interchangeably to index the same dictionary entry.
- class dict(**kwargs)¶
- class dict(mapping, /, **kwargs)
- class dict(iterable, /, **kwargs)
Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
Dictionaries can be created by several means:
Use a comma-separated list of
key: valuepairs within braces:{'jack': 4098, 'sjoerd': 4127}or{4098: 'jack', 4127: 'sjoerd'}Use a dict comprehension:
{},{x: x ** 2 for x in range(10)}Use the type constructor:
dict(),dict([('foo', 100), ('bar', 200)]),dict(foo=100, bar=200)
If no positional argument is given, an empty dictionary is created. If a positional argument is given and it defines a
keys()method, a dictionary is created by calling__getitem__()on the argument with each returned key from the method. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two elements. The first element of each item becomes a key in the new dictionary, and the second element the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.
Dictionaries compare equal if and only if they have the same
(key, value)pairs (regardless of ordering). Order comparisons (’<’, ’<=’, ’>=’, ’>’) raiseTypeError. To illustrate dictionary creation and equality, the following examples all return a dictionary equal to{"one": 1, "two": 2, "three": 3}:>>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> f = dict({'one': 1, 'three': 3}, two=2) >>> a == b == c == d == e == f True
Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4} >>> d {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> list(d) ['one', 'two', 'three', 'four'] >>> list(d.values()) [1, 2, 3, 4] >>> d["one"] = 42 >>> d {'one': 42, 'two': 2, 'three': 3, 'four': 4} >>> del d["two"] >>> d["two"] = None >>> d {'one': 42, 'three': 3, 'four': 4, 'two': None}
Förändrat i version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
These are the operations that dictionaries support (and therefore, custom mapping types should support too):
- list(d)
Return a list of all the keys used in the dictionary d.
- len(d)
Return the number of items in the dictionary d.
- d[key]
Return the item of d with key key. Raises a
KeyErrorif key is not in the map.If a subclass of dict defines a method
__missing__()and key is not present, thed[key]operation calls that method with the key key as argument. Thed[key]operation then returns or raises whatever is returned or raised by the__missing__(key)call. No other operations or methods invoke__missing__(). If__missing__()is not defined,KeyErroris raised.__missing__()must be a method; it cannot be an instance variable:>>> class Counter(dict): ... def __missing__(self, key): ... return 0 ... >>> c = Counter() >>> c['red'] 0 >>> c['red'] += 1 >>> c['red'] 1
The example above shows part of the implementation of
collections.Counter. A different__missing__()method is used bycollections.defaultdict.
- d[key] = value
Set
d[key]to value.
- del d[key]
Remove
d[key]from d. Raises aKeyErrorif key is not in the map.
- key in d
Return
Trueif d has a key key, elseFalse.
- key not in d
Equivalent to
not key in d.
- iter(d)
Return an iterator over the keys of the dictionary. This is a shortcut for
iter(d.keys()).
- clear()¶
Remove all items from the dictionary.
- copy()¶
Return a shallow copy of the dictionary.
- classmethod fromkeys(iterable, value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
fromkeys()is a class method that returns a new dictionary. value defaults toNone. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.
- get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to
None, so that this method never raises aKeyError.
- items()¶
Return a new view of the dictionary’s items (
(key, value)pairs). See the documentation of view objects.
- keys()¶
Return a new view of the dictionary’s keys. See the documentation of view objects.
- pop(key, /)¶
- pop(key, default, /)
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a
KeyErroris raised.
- popitem()¶
Remove and return a
(key, value)pair from the dictionary. Pairs are returned in LIFO order.popitem()is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, callingpopitem()raises aKeyError.Förändrat i version 3.7: LIFO order is now guaranteed. In prior versions,
popitem()would return an arbitrary key/value pair.
- reversed(d)
Return a reverse iterator over the keys of the dictionary. This is a shortcut for
reversed(d.keys()).Added in version 3.8.
- setdefault(key, default=None, /)¶
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to
None.
- update(**kwargs)¶
- update(mapping, /, **kwargs)
- update(iterable, /, **kwargs)
Update the dictionary with the key/value pairs from mapping or iterable and kwargs, overwriting existing keys. Return
None.update()accepts either another object with akeys()method (in which case__getitem__()is called with every key returned from the method) or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs:d.update(red=1, blue=2).
- values()¶
Return a new view of the dictionary’s values. See the documentation of view objects.
An equality comparison between one
dict.values()view and another will always returnFalse. This also applies when comparingdict.values()to itself:>>> d = {'a': 1} >>> d.values() == d.values() False
- d | other
Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys.
Added in version 3.9.
- d |= other
Update the dictionary d with keys and values from other, which may be either a mapping or an iterable of key/value pairs. The values of other take priority when d and other share keys.
Added in version 3.9.
Dictionaries and dictionary views are reversible.
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4} >>> d {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> list(reversed(d)) ['four', 'three', 'two', 'one'] >>> list(reversed(d.values())) [4, 3, 2, 1] >>> list(reversed(d.items())) [('four', 4), ('three', 3), ('two', 2), ('one', 1)]
Förändrat i version 3.8: Dictionaries are now reversible.
Se även
types.MappingProxyType can be used to create a read-only view
of a dict.
Se även
For detailed information on thread-safety guarantees for dict
objects, see Thread safety for dict objects.
Dictionary view objects¶
The objects returned by dict.keys(), dict.values() and
dict.items() are view objects. They provide a dynamic view on the
dictionary’s entries, which means that when the dictionary changes, the view
reflects these changes.
Dictionary views can be iterated over to yield their respective data, and support membership tests:
- len(dictview)
Return the number of entries in the dictionary.
- iter(dictview)
Return an iterator over the keys, values or items (represented as tuples of
(key, value)) in the dictionary.Keys and values are iterated over in insertion order. This allows the creation of
(value, key)pairs usingzip():pairs = zip(d.values(), d.keys()). Another way to create the same list ispairs = [(v, k) for (k, v) in d.items()].Iterating views while adding or deleting entries in the dictionary may raise a
RuntimeErroror fail to iterate over all entries.Förändrat i version 3.7: Dictionary order is guaranteed to be insertion order.
- x in dictview
Return
Trueif x is in the underlying dictionary’s keys, values or items (in the latter case, x should be a(key, value)tuple).
- reversed(dictview)
Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion.
Förändrat i version 3.8: Dictionary views are now reversible.
- dictview.mapping
Return a
types.MappingProxyTypethat wraps the original dictionary to which the view refers.Added in version 3.10.
Keys views are set-like since their entries are unique and hashable.
Items views also have set-like operations since the (key, value) pairs
are unique and the keys are hashable.
If all values in an items view are hashable as well,
then the items view can interoperate with other sets.
(Values views are not treated as set-like
since the entries are generally not unique.) For set-like views, all of the
operations defined for the abstract base class collections.abc.Set are
available (for example, ==, <, or ^). While using set operators,
set-like views accept any iterable as the other operand,
unlike sets which only accept sets as the input.
An example of dictionary view usage:
>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()
>>> # iteration
>>> n = 0
>>> for val in values:
... n += val
...
>>> print(n)
504
>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]
>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']
>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
True
>>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
True
>>> # get back a read-only proxy for the original dictionary
>>> values.mapping
mappingproxy({'bacon': 1, 'spam': 500})
>>> values.mapping['spam']
500
Context Manager Types¶
Python’s with statement supports the concept of a runtime context
defined by a context manager. This is implemented using a pair of methods
that allow user-defined classes to define a runtime context that is entered
before the statement body is executed and exited when the statement ends:
- contextmanager.__enter__()¶
Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the
asclause ofwithstatements using this context manager.An example of a context manager that returns itself is a file object. File objects return themselves from __enter__() to allow
open()to be used as the context expression in awithstatement.An example of a context manager that returns a related object is the one returned by
decimal.localcontext(). These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of thewithstatement without affecting code outside thewithstatement.
- contextmanager.__exit__(exc_type, exc_val, exc_tb)¶
Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the
withstatement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments areNone.Returning a true value from this method will cause the
withstatement to suppress the exception and continue execution with the statement immediately following thewithstatement. Otherwise the exception continues propagating after this method has finished executing.If this method raises an exception while handling an earlier exception from the
withblock, the new exception is raised, and the original exception is stored in its__context__attribute.The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code to easily detect whether or not an
__exit__()method has actually failed.
Python defines several context managers to support easy thread synchronisation,
prompt closure of files or other objects, and simpler manipulation of the active
decimal arithmetic context. The specific types are not treated specially beyond
their implementation of the context management protocol. See the
contextlib module for some examples.
Python’s generators and the contextlib.contextmanager decorator
provide a convenient way to implement these protocols. If a generator function is
decorated with the contextlib.contextmanager decorator, it will return a
context manager implementing the necessary __enter__() and
__exit__() methods, rather than the iterator produced by an
undecorated generator function.
Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible.
Type Annotation Types — Generic Alias, Union¶
The core built-in types for type annotations are Generic Alias and Union.
Generic Alias Type¶
GenericAlias objects are generally created by
subscripting a class. They are most often used with
container classes, such as list or
dict. For example, list[int] is a GenericAlias object created
by subscripting the list class with the argument int.
GenericAlias objects are intended primarily for use with
type annotations.
Observera
It is generally only possible to subscript a class if the class implements
the special method __class_getitem__().
A GenericAlias object acts as a proxy for a generic type,
implementing parameterized generics.
For a container class, the
argument(s) supplied to a subscription of the class may
indicate the type(s) of the elements an object contains. For example,
set[bytes] can be used in type annotations to signify a set in
which all the elements are of type bytes.
For a class which defines __class_getitem__() but is not a
container, the argument(s) supplied to a subscription of the class will often
indicate the return type(s) of one or more methods defined on an object. For
example, regular expressions can be used on both the str data
type and the bytes data type:
If
x = re.search('foo', 'foo'),xwill be a re.Match object where the return values ofx.group(0)andx[0]will both be of typestr. We can represent this kind of object in type annotations with theGenericAliasre.Match[str].If
y = re.search(b'bar', b'bar'), (note thebforbytes),ywill also be an instance ofre.Match, but the return values ofy.group(0)andy[0]will both be of typebytes. In type annotations, we would represent this variety of re.Match objects withre.Match[bytes].
GenericAlias objects are instances of the class
types.GenericAlias, which can also be used to create GenericAlias
objects directly.
- T[X, Y, ...]
Creates a
GenericAliasrepresenting a typeTparameterized by types X, Y, and more depending on theTused. For example, a function expecting alistcontainingfloatelements:def average(values: list[float]) -> float: return sum(values) / len(values)
Another example for mapping objects, using a
dict, which is a generic type expecting two type parameters representing the key type and the value type. In this example, the function expects adictwith keys of typestrand values of typeint:def send_post_request(url: str, body: dict[str, int]) -> None: ...
The builtin functions isinstance() and issubclass() do not accept
GenericAlias types for their second argument:
>>> isinstance([1, 2], list[str])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() argument 2 cannot be a parameterized generic
The Python runtime does not enforce type annotations.
This extends to generic types and their type parameters. When creating
a container object from a GenericAlias, the elements in the container are not checked
against their type. For example, the following code is discouraged, but will
run without errors:
>>> t = list[str]
>>> t([1, 2, 3])
[1, 2, 3]
Furthermore, parameterized generics erase type parameters during object creation:
>>> t = list[str]
>>> type(t)
<class 'types.GenericAlias'>
>>> l = t()
>>> type(l)
<class 'list'>
Calling repr() or str() on a generic shows the parameterized type:
>>> repr(list[int])
'list[int]'
>>> str(list[int])
'list[int]'
The __getitem__() method of generic containers will raise an
exception to disallow mistakes like dict[str][str]:
>>> dict[str][str]
Traceback (most recent call last):
...
TypeError: dict[str] is not a generic class
Sådana uttryck är dock giltiga när typvariabler används. Indexet måste ha lika många element som det finns typvariabler i objektet GenericAlias:s __args__.
>>> from typing import TypeVar
>>> Y = TypeVar('Y')
>>> dict[str, Y][int]
dict[str, int]
Generiska standardklasser¶
Följande klasser i standardbiblioteket stöder parametriserade generiker. Denna lista är inte uttömmande.
listatypsamlingar.defaultdictsamlingar.OrderedDictsamlingar.Räknaresamlingar.ChainMapdataklasser.fält
Särskilda attribut för GenericAlias-objekt¶
Alla parametriserade generics implementerar speciella skrivskyddade attribut.
- genericalias.__origin__¶
Detta attribut pekar på den icke-parameteriserade generiska klassen:
>>> list[int].__origin__ <class 'list'>
- genericalias.__args__¶
Detta attribut är en
tuple(eventuellt av längd 1) av generiska typer som skickas till den ursprungliga__class_getitem__()av den generiska klassen:>>> dict[str, list[int]].__args__ (<class 'str'>, list[int])
- genericalias.__parameters__¶
Detta attribut är en latent beräknad tupel (eventuellt tom) av unika typvariabler som finns i
__args__:>>> from typing import TypeVar >>> T = TypeVar('T') >>> list[T].__parameters__ (~T,)
Observera
Ett
GenericAlias-objekt medtyping.ParamSpec-parametrar kanske inte har korrekta__parameters__efter substitution eftersomtyping.ParamSpecfrämst är avsedd för statisk typkontroll.
- genericalias.__unpacked__¶
En boolean som är sann om aliaset har packats upp med operatorn
*(seTypeVarTuple).Added in version 3.11.
Se även
- PEP 484 - Tips om typ
Introduktion till Pythons ramverk för typannoteringar.
- PEP 585 - Typhintning av generiska i standardsamlingar
Introducerar möjligheten att naturligt parametrisera standardbiblioteksklasser, förutsatt att de implementerar den speciella klassmetoden
__class_getitem__().- Generics, användardefinierad generik och
typing.Generic Dokumentation om hur man implementerar generiska klasser som kan parametriseras vid körning och förstås av statiska typkontrollanter.
Added in version 3.9.
Typ av fackförening¶
Ett union-objekt innehåller värdet av |-operationen (bitvis eller) på flera type-objekt. Dessa typer är främst avsedda för type annotations. Uttrycket unionstyp möjliggör en renare syntax för typhinting jämfört med subskription av typing.Union.
- X | Y | ...
Definierar ett union-objekt som innehåller typerna X, Y, och så vidare.
X | Ybetyder antingen X eller Y. Det är ekvivalent medtyping.Union[X, Y]. Till exempel förväntar sig följande funktion ett argument av typenintellerfloat:def square(number: int | float) -> int | float: returnerar nummer ** 2
Observera
Operanden
|kan inte användas vid körning för att definiera unioner där en eller flera medlemmar är en framåtriktad referens. Till exempel kommerint | "Foo", där"Foo"är en referens till en klass som ännu inte definierats, att misslyckas vid körning. För unioner som innehåller framåtriktade referenser ska hela uttrycket presenteras som en sträng, t.ex."int | Foo".
- union_object == other
Unionsobjekt kan testas för jämlikhet med andra unionsobjekt. Detaljerad information:
Unioner av unioner är tillplattade:
(int | str) | float == int | str | float
Överflödiga typer tas bort:
int | str | int == int | str
Vid jämförelse av fackföreningar ignoreras ordningen:
int | str == str | int
Den skapar instanser av
typing.Union:int | str == typing.Union[int, str] typ(int | str) är typing.union
Valfria typer kan stavas som en union med
None:str | None == typing.Optional[str]
- isinstance(obj, union_object)
- issubclass(obj, union_object)
Anrop till
isinstance()ochissubclass()stöds också med ett unionsobjekt:>>> isinstance("", int | str) True
Däremot kan parameterized generics i unionsobjekt inte kontrolleras:
>>> isinstance(1, int | list[int]) # short-circuit evaluation True >>> isinstance([1], int | list[int]) Traceback (most recent call last): ... TypeError: isinstance() argument 2 cannot be a parameterized generic
Den användardefinierade typen för union-objektet kan hämtas från typing.Union och användas för isinstance()-kontroller:
>>> import typing
>>> isinstance(int | str, typing.Union)
True
>>> typing.Union()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create 'typing.Union' instances
Observera
Metoden __or__() för typobjekt har lagts till för att stödja syntaxen X | Y. Om en metaklass implementerar __or__() kan unionen åsidosätta den:
>>> class M(type):
... def __or__(self, other):
... return "Hello"
...
>>> class C(metaclass=M):
... pass
...
>>> C | int
'Hello'
>>> int | C
int | C
Se även
PEP 604 – PEP föreslår syntaxen X | Y och Union-typen.
Added in version 3.10.
Förändrat i version 3.14: Union-objekt är nu instanser av typing.Union. Tidigare var de instanser av types.UnionType, som fortfarande är ett alias för typing.Union.
Andra inbyggda typer¶
Tolken har stöd för flera andra typer av objekt. De flesta av dessa stöder endast en eller två operationer.
Moduler¶
Den enda speciella operationen på en modul är attributåtkomst: m.name, där m är en modul och name ger åtkomst till ett namn som definieras i m:s symboltabell. Modulattribut kan tilldelas till. (Observera att import inte i strikt mening är en operation på ett modulobjekt; import foo kräver inte att ett modulobjekt med namnet foo existerar, utan snarare att det finns en (extern) definition för en modul med namnet foo någonstans)
Ett speciellt attribut för varje modul är __dict__. Detta är den ordbok som innehåller modulens symboltabell. Modifiering av denna dictionary kommer faktiskt att ändra modulens symboltabell, men direkt tilldelning till attributet __dict__ är inte möjligt (du kan skriva m.__dict__['a'] = 1, vilket definierar m.a till att vara 1, men du kan inte skriva m.__dict__ = {}). Att ändra __dict__ direkt är inte rekommenderat.
Moduler som är inbyggda i tolken skrivs på följande sätt: <modulen 'sys' (inbyggd)>. Om de laddas från en fil skrivs de som <modulen 'os' från '/usr/local/lib/pythonX.Y/os.pyc'>.
Klasser och klassinstanser¶
Se Objects, values and types och Class definitions för dessa.
Funktioner¶
Funktionsobjekt skapas av funktionsdefinitioner. Den enda operationen på ett funktionsobjekt är att anropa det: func(argument-list).
Det finns egentligen två olika typer av funktionsobjekt: inbyggda funktioner och användardefinierade funktioner. Båda stöder samma operation (att anropa funktionen), men implementeringen är olika, därav de olika objekttyperna.
Se Function definitions för mer information.
Metoder¶
Methods are functions that are called using the attribute notation.
There are two flavors: built-in methods
(such as append() on lists)
and class instance method.
Built-in methods are described with the types that support them.
Om du anropar en metod (en funktion som definieras i en klassnamnrymd) via en instans får du ett speciellt objekt: ett bound method-objekt (även kallat instance method). När den anropas kommer den att lägga till argumentet self i argumentlistan. Bound methods har två speciella skrivskyddade attribut: m.__self__ är det objekt som metoden verkar på, och m.__func__ är den funktion som implementerar metoden. Anrop av m(arg-1, arg-2, ..., arg-n) är helt likvärdigt med anrop av m.__func__(m.__self__, arg-1, arg-2, ..., arg-n).
Liksom funktionsobjekt, stöder bundna metodobjekt att få godtyckliga attribut. Men eftersom metodattribut faktiskt lagras på det underliggande funktionsobjektet (method.__func__) är det inte tillåtet att ställa in metodattribut på bundna metoder. Försök att sätta ett attribut på en metod resulterar i ett AttributeError. För att kunna ställa in ett metodattribut måste du uttryckligen ställa in det på det underliggande funktionsobjektet:
>>> class C:
... def method(self):
... pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method' # can't set on the method
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'method' object has no attribute 'whoami'
>>> c.method.__func__.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'
Se Instance methods för mer information.
Kodobjekt¶
Kodobjekt används av implementationen för att representera ”pseudokompilerad” körbar Python-kod, t.ex. en funktionskropp. De skiljer sig från funktionsobjekt eftersom de inte innehåller någon referens till sin globala exekveringsmiljö. Kodobjekt returneras av den inbyggda compile()-funktionen och kan extraheras från funktionsobjekt genom deras __code__-attribut. Se även modulen code.
Åtkomst till __code__ genererar ett auditing event object.__getattr__ med argumenten obj och "__code__".
Ett kodobjekt kan exekveras eller utvärderas genom att skicka det (i stället för en källsträng) till de inbyggda funktionerna exec() eller eval().
Se The standard type hierarchy för mer information.
Typ av objekt¶
Typobjekt representerar de olika objekttyperna. Ett objekts typ nås med den inbyggda funktionen type(). Det finns inga speciella operationer på typer. Standardmodulen types definierar namn för alla inbyggda standardtyper.
Typer skrivs på detta sätt: <klass 'int'>.
Null-objektet¶
Detta objekt returneras av funktioner som inte uttryckligen returnerar ett värde. Det stöder inga speciella operationer. Det finns exakt ett null-objekt, med namnet None (ett inbyggt namn). type(None)() producerar samma singleton.
Det är skrivet som None.
Ellipsis-objektet¶
This object is commonly used to indicate that something is omitted.
It supports no special operations. There is exactly one ellipsis object, named
Ellipsis (a built-in name). type(Ellipsis)() produces the
Ellipsis singleton.
Det skrivs som Ellipsis eller ....
In typical use, ... as the Ellipsis object appears in a few different
places, for instance:
In type annotations, such as callable arguments or tuple elements.
As the body of a function instead of a pass statement.
In third-party libraries, such as Numpy’s slicing and striding.
Python also uses three dots in ways that are not Ellipsis objects, for instance:
Doctest’s
ELLIPSIS, as a pattern for missing content.The default Python prompt of the interactive shell when partial input is incomplete.
Lastly, the Python documentation often uses three dots in conventional English
usage to mean omitted content, even in code examples that also use them as the
Ellipsis.
Det icke implementerade objektet¶
Detta objekt returneras från jämförelser och binära operationer när de ombeds att använda typer som de inte stöder. Se Comparisons för mer information. Det finns exakt ett NotImplemented-objekt. type(NotImplemented)() producerar singleton-instansen.
Den är skriven som NotImplemented.
Interna objekt¶
Se The standard type hierarchy för denna information. Den beskriver stack frame objects, traceback objects, och slice objects.
Särskilda egenskaper¶
Implementationen lägger till några speciella skrivskyddade attribut till flera objekttyper, där de är relevanta. Vissa av dessa rapporteras inte av den inbyggda funktionen dir().
- definition.__name__¶
Namnet på klassen, funktionen, metoden, deskriptorn eller generatorinstansen.
- definition.__qualname__¶
Det qualified name på klassen, funktionen, metoden, deskriptorn eller generatorinstansen.
Added in version 3.3.
- definition.__module__¶
Namnet på den modul i vilken en klass eller funktion definierades.
- definition.__doc__¶
Dokumentationssträngen för en klass eller funktion, eller
Noneom den är odefinierad.
- definition.__type_params__¶
typ-parametrarna för generiska klasser, funktioner och typ-alias. För klasser och funktioner som inte är generiska kommer detta att vara en tom tupel.
Added in version 3.12.
Längdbegränsning för konvertering av heltalssträngar¶
CPython har en global gräns för konvertering mellan int och str för att motverka överbelastningsattacker. Denna gräns gäller endast för decimaltal eller andra talbaser som inte har två potenser. Hexadecimala, oktala och binära konverteringar är obegränsade. Gränsen kan konfigureras.
Typen int i CPython är ett tal av godtycklig längd som lagras i binär form (allmänt känt som ett ”bignum”). Det finns ingen algoritm som kan konvertera en sträng till ett binärt heltal eller ett binärt heltal till en sträng i linjär tid, om inte basen är en potens av 2. Även de mest kända algoritmerna för bas 10 har subkvadratisk komplexitet. Att konvertera ett stort värde som int('1' * 500_000) kan ta över en sekund på en snabb CPU.
Att begränsa konverteringsstorleken är ett praktiskt sätt att undvika CVE 2020-10735.
Gränsen tillämpas på antalet siffertecken i in- eller utdatasträngen när en icke-linjär konverteringsalgoritm skulle vara inblandad. Underscorer och tecknet räknas inte med i begränsningen.
När en operation skulle överskrida gränsen genereras ett ValueError:
>>> import sys
>>> sys.set_int_max_str_digits(4300) # Illustrative, this is the default.
>>> _ = int('2' * 5432)
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit
>>> i = int('2' * 4300)
>>> len(str(i))
4300
>>> i_squared = i*i
>>> len(str(i_squared))
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
>>> len(hex(i_squared))
7144
>>> assert int(hex(i_squared), base=16) == i*i # Hexadecimal is unlimited.
The default limit is 4300 digits as provided in
sys.int_info.default_max_str_digits.
The lowest limit that can be configured is 640 digits as provided in
sys.int_info.str_digits_check_threshold.
Verification:
>>> import sys
>>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
>>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
>>> msg = int('578966293710682886880994035146873798396722250538762761564'
... '9252925514383915483333812743580549779436104706260696366600'
... '571186405732').to_bytes(53, 'big')
...
Added in version 3.11.
Affected APIs¶
The limitation only applies to potentially slow conversions between int
and str or bytes:
int(string)with default base 10.int(string, base)for all bases that are not a power of 2.str(integer).repr(integer).any other string conversion to base 10, for example
f"{integer}","{}".format(integer), orb"%d" % integer.
The limitations do not apply to functions with a linear algorithm:
int(string, base)with base 2, 4, 8, 16, or 32.Format specification mini-language for hex, octal, and binary numbers.
strtodecimal.Decimal.
Configuring the limit¶
Before Python starts up you can use an environment variable or an interpreter command line flag to configure the limit:
PYTHONINTMAXSTRDIGITS, e.g.PYTHONINTMAXSTRDIGITS=640 python3to set the limit to 640 orPYTHONINTMAXSTRDIGITS=0 python3to disable the limitation.-X int_max_str_digits, e.g.python3 -X int_max_str_digits=640sys.flags.int_max_str_digitscontains the value ofPYTHONINTMAXSTRDIGITSor-X int_max_str_digits. If both the env var and the-Xoption are set, the-Xoption takes precedence. A value of -1 indicates that both were unset, thus a value ofsys.int_info.default_max_str_digitswas used during initialization.
From code, you can inspect the current limit and set a new one using these
sys APIs:
sys.get_int_max_str_digits()andsys.set_int_max_str_digits()are a getter and setter for the interpreter-wide limit. Subinterpreters have their own limit.
Information about the default and minimum can be found in sys.int_info:
sys.int_info.default_max_str_digitsis the compiled-in default limit.sys.int_info.str_digits_check_thresholdis the lowest accepted value for the limit (other than 0 which disables it).
Added in version 3.11.
Varning
Setting a low limit can lead to problems. While rare, code exists that
contains integer constants in decimal in their source that exceed the
minimum threshold. A consequence of setting the limit is that Python source
code containing decimal integer literals longer than the limit will
encounter an error during parsing, usually at startup time or import time or
even at installation time - anytime an up to date .pyc does not already
exist for the code. A workaround for source that contains such large
constants is to convert them to 0x hexadecimal form as it has no limit.
Test your application thoroughly if you use a low limit. Ensure your tests
run with the limit set early via the environment or flag so that it applies
during startup and even during any installation step that may invoke Python
to precompile .py sources to .pyc files.
Recommended configuration¶
The default sys.int_info.default_max_str_digits is expected to be
reasonable for most applications. If your application requires a different
limit, set it from your main entry point using Python version agnostic code as
these APIs were added in security patch releases in versions before 3.12.
Example:
>>> import sys
>>> if hasattr(sys, "set_int_max_str_digits"):
... upper_bound = 68000
... lower_bound = 4004
... current_limit = sys.get_int_max_str_digits()
... if current_limit == 0 or current_limit > upper_bound:
... sys.set_int_max_str_digits(upper_bound)
... elif current_limit < lower_bound:
... sys.set_int_max_str_digits(lower_bound)
If you need to disable it entirely, set it to 0.
Footnotes