Pythoni stringi vorming ()

Stringi format () meetod vormindab antud stringi Pythonis kenamaks väljundiks.

Meetodi süntaks format()on:

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

Siin on p0, p1, … positsioonilised argumendid ja k0, k1, … on märksõnade argumendid vastavalt väärtusega v0, v1 ja ….

Ja mall on segu vormingukoodidest koos argumentide kohahoidjatega.

Stringi formaat () Parameetrid

format()meetod võtab suvalise arvu parameetreid. Kuid see on jagatud kahte tüüpi parameetriteks:

  • Asukohaparameetrid - loetelu parameetritest, millele pääseb juurde lokkisulgudes olevate parameetrite indeksiga(index)
  • Märksõna parameetrid - tüübi key = value parameetrite loend, millele pääseb juurde lokkisulgudes parameetri võtmega(key)

Tagastusväärtus stringi vormingust ()

format()Meetod tagastab vormindatud stringi.

Kuidas Stringi formaat () töötab?

format()Loeb tüüpi argumentide seda ja vormindab ta vormi kohaselt määratletud koode string.

Positsiooniliste argumentide jaoks

Asendiargumendid

Argument 0 on siin string "Adam" ja argument 1 on ujuv arv 230.2346.

Märkus. Argumentide loend algab Pythonis 0-st.

String "Hello (0), your balance is (1:9.3f)"on mallistring. See sisaldab vormindamise vormingukoode.

Lokkisulgurid on vaid argumentide paigutamiseks kohatäited. Ülaltoodud näites on (0) "Aadama" kohatäide ja (1: 9.3f) kohatäide 230,2346 jaoks.

Kuna malli string viitab format()argumentidele kui (0)ja (1), on argumendid positsioonilised argumendid. Mõlemale saab viidata ka ilma numbriteta ()ja Python teisendab need sisemiselt numbriteks.

Sisemiselt,

  • Kuna "Adam" on 0 th argumenti, siis pannakse asemele (0). Kuna (0)see ei sisalda muid vormingukoode, ei tee see muid toiminguid.
  • Esimese argumendi 230.2346 puhul pole see aga nii . Siin (1:9.3f)asetab 230.2346 oma kohale ja teostab operatsiooni 9.3f.
  • f määrab, et vorming tegeleb ujukarvuga. Kui seda pole õigesti täpsustatud, annab see vea.
  • Osa enne tähte "." (9) määrab minimaalse laiuse / polstri, mida number (230.2346) võib võtta. Sel juhul eraldatakse 230,2346 minimaalselt 9 kohta koos tähega.
    Kui ühtlustamisvalikut pole määratud, joondatakse see ülejäänud tühikutest paremale. (Stringide puhul on see joondatud vasakule.)
  • Osa pärast tähte "." (3) kärbib kümnendosa (2346) etteantud numbrini. Sellisel juhul kärbitakse 2346 kolme koha järel.
    Ülejäänud numbrid (46) on ümardatud, väljastades 235.

Märksõna argumentide jaoks

Märksõna argumendid

Oleme kasutanud sama ülaltoodud näidet märksõna ja positsiooni argumentide erinevuse näitamiseks.

Siin oleme parameetrite asemel kasutanud parameetrite asemel võtmeväärtust. Nimelt nimi = "Adam" ja blc = 230,2346.

Kuna nende parameetrite puhul on nende võtmed viidatud kui (nimi) ja (blc: 9.3f), on need tuntud kui märksõnad või nimega argumendid.

Sisemiselt,

  • Kohatäide (nimi) asendatakse nime väärtusega - "Adam". Kuna see ei sisalda muid vormingukoode, paigutatakse "Adam".
  • Argumendi blc = 230.2346 korral asendatakse kohahoidja (blc: 9.3f) väärtusega 230.2346. Kuid enne selle asendamist, nagu eelmine näide, teostab see sellega operatsiooni 9.3f.
    See väljastab 230.235. Kümnendosa kärbitakse pärast kolme kohta ja ülejäänud numbrid ümardatakse. Samamoodi määratakse kogulaius 9, jättes vasakule kaks tühikut.

Põhivorming koos vorminguga ()

format()Meetod võimaldab kasutada lihtsat kohahoidjad vormingu.

Näide 1: vaikeväärtuste, positsioonide ja märksõnade põhivorming

 # 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))

Väljund

Tere, Adam, teie saldo on 230,2346. Tere, Adam, teie saldo on 230,2346. Tere, Adam, teie saldo on 230,2346. Tere, Adam, teie saldo on 230,2346.

Märkus . Segatud argumentide korral peavad märksõna argumendid alati järgima positsiooni argumente.

Numbrite vormindamine vorminguga ()

Numbreid saate vormindada alltoodud vorminguspetsifikaatori abil:

Numbrivormingu tüübid
Tüüp Tähendus
d Koma täisarv
c Vastav Unicode'i märk
b Binaarne formaat
o Oktaalformaat
x Kuueteistkümnendsüsteemi formaat (väiketähed)
X Kuueteistkümnendsüsteemi formaat (suurtäht)
n Sama mis 'd'. Välja arvatud see, et see kasutab numbrite eraldaja jaoks praegust lokaadi sätet
e Eksponentsiaalne märge. (väike täht e)
E Eksponentsiaalne märge (suurtäht E)
f Kuvab fikseeritud punkti numbri (vaikimisi: 6)
F Sama mis 'f'. Välja arvatud „INF” kui „INF” ja „nan” kui „NAN”
g Üldine formaat. Ümardab numbri p olulise numbrini. (Vaiketäpsus: 6)
G Sama mis 'g'. Välja arvatud lülitamine tähele „E”, kui arv on suur.
% Protsent. Korrutab 100-ga ja paneb lõppu%.

Näide 2: Numbrite lihtne vormindamine

 # 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))

Väljund

 Number on: 123 Number on: 123.456790 prügikast: 1100, okt: 14, kuuskant: c

Näide 3: Numbrivorming koos int ja ujukite polsterdusega

 # 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))

Väljund

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

Siin,

  • võtab esimeses lauses (:5d)täisarvu argumendi ja määrab minimaalse laiuse 5. Kuna joondust pole määratud, joondatakse see paremale.
  • 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

Numbrivorming koos joondusega

Operaatoreid and =kasutatakse joondamiseks, kui neile määratakse teatud laius.

Numbrivorming koos joondusega
Tüüp Tähendus
< Vasakule joondatud ülejäänud ruumiga
^ Keskel joondatud ülejäänud ruumi järgi
> Paremale joondatud ülejäänud ruumiga
= Sundib allkirjastatud (+) (-) vasakpoolsesse asendisse

Näide 5: arvu vormindamine vasakule, paremale ja keskele joondusega

 # 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))

Väljund

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

Märkus: täisarvude nullidega täidetud vasak joondamine võib põhjustada probleeme kui 3. näide, mis tagastab 12000 asemel 12.

Stringi vormindamine vorminguga ()

Numbritena saab stringi vormindada sarnaselt 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)

Objekti __str__()ja __repr__()funktsionaalsust saate kasutada ka käsiraamatuga format().

Nagu näiteks __format__(), saate objekti __str__()ja __repr_()meetodid hõlpsasti alistada .

Näide 12: __str () __ ja __repr () __ lühike! R ja! S, kasutades vormingut ()

 # __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()))

Väljund

 Tsitaadid: 'kass', ilma jutumärkideta: kassi repr: REPR, str: STR 

Huvitavad Artiklid...