Python String-indeling ()

De string format () methode formatteert de gegeven string in een mooiere uitvoer in Python.

De syntaxis van de format()methode is:

 template.format (p0, p1, …, k0 = v0, k1 = v1, …)

Hier zijn p0, p1,… positionele argumenten en k0, k1,… zijn trefwoordargumenten met respectievelijk waarden v0, v1,….

En sjabloon is een combinatie van opmaakcodes met tijdelijke aanduidingen voor de argumenten.

Tekenreeksformaat () Parameters

format()methode heeft een willekeurig aantal parameters. Maar is onderverdeeld in twee soorten parameters:

  • Positionele parameters - lijst met parameters die toegankelijk zijn met de index van de parameter tussen accolades(index)
  • Trefwoordparameters - lijst met parameters van het type key = value, waartoe toegang kan worden verkregen met de sleutel van de parameter tussen accolades(key)

Retourwaarde van String-indeling ()

De format()methode retourneert de opgemaakte tekenreeks.

Hoe String-indeling () werkt?

Het format()leest het type argumenten dat eraan wordt doorgegeven en maakt het op volgens de formaatcodes die in de string zijn gedefinieerd.

Voor positionele argumenten

Positionele argumenten

Hier is argument 0 een tekenreeks "Adam" en argument 1 is een zwevend getal 230.2346.

Opmerking: argumentenlijst begint bij 0 in Python.

De string "Hello (0), your balance is (1:9.3f)"is de template-string. Dit bevat de formaatcodes voor opmaak.

De accolades zijn slechts tijdelijke aanduidingen voor de argumenten die moeten worden geplaatst. In het bovenstaande voorbeeld is (0) tijdelijke aanduiding voor "Adam" en (1: 9.3f) tijdelijke aanduiding voor 230.2346.

Omdat de sjabloontekenreeks verwijst naar format()argumenten als (0)en (1), zijn de argumenten positionele argumenten. Er kan ook naar beide worden verwezen zonder de getallen zoals ()en Python converteert ze intern naar getallen.

Intern,

  • Omdat "Adam" het 0 ste argument is, wordt het in de plaats van (0). Omdat (0)het geen andere formaatcodes bevat, voert het geen andere bewerkingen uit.
  • Het is echter niet het geval voor 1 st argument 230,2346. Hier (1:9.3f)plaatst 230.2346 op zijn plaats en voert de bewerking 9.3f uit.
  • f specificeert dat het formaat te maken heeft met een float-getal. Als het niet correct is gespecificeerd, zal het een foutmelding geven.
  • Het deel voor de "." (9) specificeert de minimale breedte / opvulling die het nummer (230.2346) kan hebben. In dit geval krijgt 230.2346 minimaal 9 plaatsen inclusief de ".".
    Als er geen uitlijningsoptie is opgegeven, wordt deze rechts van de resterende spaties uitgelijnd. (Voor tekenreeksen is het links uitgelijnd.)
  • Het gedeelte na de "." (3) kapt het decimale deel (2346) af tot aan het opgegeven getal. In dit geval wordt 2346 afgekapt na 3 plaatsen.
    De resterende cijfers (46) worden afgerond op 235.

Voor trefwoordargumenten

Trefwoord argumenten

We hebben hetzelfde voorbeeld van hierboven gebruikt om het verschil tussen trefwoord en positionele argumenten te laten zien.

Hier hebben we in plaats van alleen de parameters een sleutelwaarde voor de parameters gebruikt. Namelijk naam = "Adam" en blc = 230.2346.

Aangezien naar deze parameters wordt verwezen door hun sleutels als (naam) en (blc: 9.3f), staan ​​ze bekend als trefwoord of benoemde argumenten.

Intern,

  • De tijdelijke aanduiding (naam) wordt vervangen door de waarde van naam - "Adam". Omdat het geen andere formaatcodes bevat, wordt "Adam" geplaatst.
  • Voor het argument blc = 230.2346 wordt de tijdelijke aanduiding (blc: 9.3f) vervangen door de waarde 230.2346. Maar voordat het wordt vervangen, zoals in het vorige voorbeeld, voert het een 9.3f-bewerking uit.
    Dit levert 230.235. Het decimale deel wordt na 3 plaatsen afgekapt en de resterende cijfers worden afgerond. Evenzo wordt de totale breedte toegewezen aan 9, waarbij er twee spaties aan de linkerkant overblijven.

Basisopmaak met indeling ()

De format()methode maakt het gebruik van eenvoudige tijdelijke aanduidingen voor opmaak mogelijk.

Voorbeeld 1: basisopmaak voor standaard-, positionele en trefwoordargumenten

 # default arguments print("Hello (), your balance is ().".format("Adam", 230.2346)) # positional arguments print("Hello (0), your balance is (1).".format("Adam", 230.2346)) # keyword arguments print("Hello (name), your balance is (blc).".format(name="Adam", blc=230.2346)) # mixed arguments print("Hello (0), your balance is (blc).".format("Adam", blc=230.2346))

Uitvoer

Hallo Adam, je saldo is 230.2346. Hallo Adam, je saldo is 230.2346. Hallo Adam, je saldo is 230.2346. Hallo Adam, je saldo is 230.2346.

Opmerking: in het geval van gemengde argumenten, moeten trefwoordargumenten altijd positionele argumenten volgen.

Getallen formatteren met format ()

U kunt getallen opmaken met behulp van de onderstaande formaatspecificatie:

Getalopmaaktypen
Type Betekenis
d Decimaal geheel getal
c Overeenkomend Unicode-teken
b Binair formaat
O Octaal formaat
X Hexadecimaal formaat (kleine letters)
X Hexadecimaal formaat (hoofdletters)
n Hetzelfde als 'd'. Behalve dat het de huidige landinstelling gebruikt voor het scheidingsteken voor nummers
e Exponentiële notatie. (kleine letter e)
E. Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'
g General format. Rounds number to p significant digits. (Default precision: 6)
G Same as 'g'. Except switches to 'E' if the number is large.
% Percentage. Multiples by 100 and puts % at the end.

Example 2: Simple number formatting

 # integer arguments print("The number is:(:d)".format(123)) # float arguments print("The float number is:(:f)".format(123.4567898)) # octal, binary and hexadecimal format print("bin: (0:b), oct: (0:o), hex: (0:x)".format(12))

Output

 The number is: 123 The number is:123.456790 bin: 1100, oct: 14, hex: c

Example 3: Number formatting with padding for int and floats

 # integer numbers with minimum width print("(:5d)".format(12)) # width doesn't work for numbers longer than padding print("(:2d)".format(1234)) # padding for float numbers print("(:8.3f)".format(12.2346)) # integer numbers with minimum width filled with zeros print("(:05d)".format(12)) # padding for float numbers filled with zeros print("(:08.3f)".format(12.2346))

Output

 1 2 1 2 3 4 1 2 . 2 3 5 0 0 0 1 2 0 0 1 2 . 2 3 5 

Here,

  • in the first statement, (:5d) takes an integer argument and assigns a minimum width of 5. Since, no alignment is specified, it is aligned to the right.
  • In the second statement, you can see the width (2) is less than the number (1234), so it doesn't take any space to the left but also doesn't truncate the number.
  • Unlike integers, floats has both integer and decimal parts. And, the mininum width defined to the number is for both parts as a whole including ".".
  • In the third statement, (:8.3f) truncates the decimal part into 3 places rounding off the last 2 digits. And, the number, now 12.235, takes a width of 8 as a whole leaving 2 places to the left.
  • If you want to fill the remaining places with zero, placing a zero before the format specifier does this. It works both for integers and floats: (:05d) and (:08.3f).

Example 4: Number formatting for signed numbers

 # show the + sign print("(:+f) (:+f)".format(12.23, -12.23)) # show the - sign only print("(:-f) (:-f)".format(12.23, -12.23)) # show space for + sign print("(: f) (: f)".format(12.23, -12.23))

Output

+12.230000 -12.230000 12.230000 -12.230000 1 2. 2 3 0 0 0 0 - 1 2. 2 3 0 0 0 0

Nummeropmaak met uitlijning

De operatoren and =worden gebruikt voor uitlijning wanneer ze een bepaalde breedte aan de nummers hebben toegewezen.

Nummeropmaak met uitlijning
Type Betekenis
< Links uitgelijnd met de resterende ruimte
^ Gecentreerd op de resterende ruimte
> Rechts uitgelijnd met de resterende ruimte
= Forceert de ondertekende (+) (-) naar de meest linkse positie

Voorbeeld 5: Getallenopmaak met links, rechts en midden uitlijning

 # integer numbers with right alignment print("(:5d)".format(12)) # float numbers with center alignment print("(:^10.3f)".format(12.2346)) # integer left alignment filled with zeros print("(:<05d)".format(12)) # float numbers with center alignment print("(:=8.3f)".format(-12.2346))

Uitvoer

1 2 1 2. 2 3 5 1 2 0 0 0 - 1 2. 2 3 5

Opmerking: Links uitlijnen gevuld met nullen voor gehele getallen kan problemen veroorzaken, aangezien het derde voorbeeld 12000 retourneert in plaats van 12.

Tekenreeksopmaak met format ()

Als getallen kan tekenreeks op dezelfde manier worden opgemaakt met format().

Example 6: String formatting with padding and alignment

 # string padding with left alignment print("(:5)".format("cat")) # string padding with right alignment print("(:>5)".format("cat")) # string padding with center alignment print("(:^5)".format("cat")) # string padding with center alignment # and '*' padding character print("(:*^5)".format("cat"))

Output

 c a t c a t c a t * c a t * 

Example 7: Truncating strings with format()

 # truncating strings to 3 letters print("(:.3)".format("caterpillar")) # truncating strings to 3 letters # and padding print("(:5.3)".format("caterpillar")) # truncating strings to 3 letters, # padding and center alignment print("(:^5.3)".format("caterpillar"))

Output

 c a t c a t c a t 

Formatting class and dictionary members using format()

Python internally uses getattr() for class members in the form ".age". And, it uses __getitem__() lookup for dictionary members in the form "(index)".

Example 8: Formatting class members using format()

 # define Person class class Person: age = 23 name = "Adam" # format age print("(p.name)'s age is: (p.age)".format(p=Person()))

Output

 Adam's age is: 23 

Here, Person object is passed as a keyword argument p.

Inside the template string, Person's name and age are accessed using .name and .age respectively.

Example 9: Formatting dictionary members using format()

 # define Person dictionary person = ('age': 23, 'name': 'Adam') # format age print("(p(name))'s age is: (p(age))".format(p=person))

Output

 Adam's age is: 23 

Similar to class, person dictionary is passed as a keyword argument p.

Inside the template string, person's name and age are accessed using (name) and (age) respectively.

There's an easier way to format dictionaries in Python using str.format(**mapping).

 # define Person dictionary person = ('age': 23, 'name': 'Adam') # format age print("(name)'s age is: (age)".format(**person))

** is a format parameter (minimum field width).

Arguments as format codes using format()

You can also pass format codes like precision, alignment, fill character as positional or keyword arguments dynamically.

Example 10: Dynamic formatting using format()

 # dynamic string format template string = "(:(fill)(align)(width))" # passing format codes as arguments print(string.format('cat', fill='*', # dynamic float format template num = "(:(align)(width).(precision)f)" # passing format codes as arguments print(num.format(123.236,>

Output

 * * c a t * * 1 2 3 . 2 4 

Here,

  • In the first example, 'cat' is the positional argument is to be formatted. Likewise, fill='*', align='^' and width=5 are keyword arguments.
  • In the template string, these keyword arguments are not retrieved as normal strings to be printed but as the actual format codes fill, align and width.
    The arguments replaces the corresponding named placeholders and the string 'cat' is formatted accordingly.
  • Likewise, in the second example, 123.236 is the positional argument and, align, width and precision are passed to the template string as format codes.

Extra formatting options with format()

format() also supports type-specific formatting options like datetime's and complex number formatting.

format() internally calls __format__() for datetime, while format() accesses the attributes of the complex number.

You can easily override the __format__() method of any object for custom formatting.

Example 11: Type-specific formatting with format() and overriding __format__() method

 import datetime # datetime formatting date = datetime.datetime.now() print("It's now: (:%Y/%m/%d %H:%M:%S)".format(date)) # complex number formatting complexNumber = 1+2j print("Real part: (0.real) and Imaginary part: (0.imag)".format(complexNumber)) # custom __format__() method class Person: def __format__(self, format): if(format == 'age'): return '23' return 'None' print("Adam's age is: (:age)".format(Person()))

Output

 It's now: 2016/12/02 04:16:28 Real part: 1.0 and Imaginary part: 2.0 Adam's age is: 23 

Here,

  • For datetime:
    Current datetime is passed as a positional argument to the format() method.
    And, internally using __format__() method, format() accesses the year, month, day, hour, minutes and seconds.
  • For complex numbers:
    1+2j is internally converted to a ComplexNumber object.
    Then accessing its attributes real and imag, the number is formatted.
  • Overriding __format__():
    Like datetime, you can override your own __format__() method for custom formatting which returns age when accessed as (:age)

U kunt ook de objecten __str__()en __repr__()functionaliteit gebruiken met steno-notaties met format().

Net als __format__(), kunt u gemakkelijk overschrijven object __str__()en __repr_()methoden.

Voorbeeld 12: __str () __ en __repr () __ steno! R en! S met format ()

 # __str__() and __repr__() shorthand !r and !s print("Quotes: (0!r), Without Quotes: (0!s)".format("cat")) # __str__() and __repr__() implementation for class class Person: def __str__(self): return "STR" def __repr__(self): return "REPR" print("repr: (p!r), str: (p!s)".format(p=Person()))

Uitvoer

 Quotes: 'cat', zonder Quotes: cat repr: REPR, str: STR 

Interessante artikelen...