---
title: Python String Formatting
description: "> ## Python String Formatting – Python мөр форматлах > > > > F-String was introduced in Python 3.6, and is now the preferred way of formatting strings. > > > > F-String нь Python 3.6-д танилцуулагдсан бөгөөд одоо мөрийг форматлах хамгийн…"
url: "https://apprentice.mn/docs/python-string-formatting/"
updated: "2024-07-31"
category: Python
---

# Python String Formatting

> ## Python String Formatting – Python мөр форматлах
>
>
>
> F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.
>
>
>
> F-String нь Python 3.6-д танилцуулагдсан бөгөөд одоо мөрийг форматлах хамгийн тохиромжтой арга юм.
>
>
>
> Before Python 3.6 we had to use the `format()` method.
>
>
>
> Python 3.6-аас өмнө `format()` аргыг ашиглаж байсан.

## F-Strings

F-string allows you to format selected parts of a string.

F-string нь мөрийн сонгосон хэсгийг форматлах боломжийг олгодог.

To specify a string as an f-string, simply put an `f` in front of the string literal, like this:

Мөрийг f-string болгон зааж өгөхийн тулд, мөрийн урд талд `f`  тэмдэглэдэг, дараах байдлаар: 

#### Example – Жишээ

Create an f-string:

f-string үүсгэх:

`txt = f"The price is 49 dollars"print(txt)`

## Placeholders and Modifiers – Орлуулагч ба өөрчлөгч

To format values in an f-string, add placeholders `{}`, a placeholder can contain variables, operations, functions, and modifiers to format the value.

F-string дотор утгуудыг форматлахын тулд орлуулагч `{}` ашигладаг. Орлуулагч дотор хувьсагч, үйлдэл, функц, эсвэл утгыг форматлах өөрчлөгч ч байж болно.

##### Example – Жишээ

Add a placeholder for the `price` variable:

`price` хувьсагчид орлуулагч нэмэх:

`price = 59txt = f"The price is {price} dollars"print(txt)`

A placeholder can also include a *modifier *to format the value.

Бас орлуулагч нь утгыг форматлахын тулд *өөрчлөгчтэй*байж болно*.*

A modifier is included by adding a colon `:` followed by a legal formatting type, like `.2f` which means fixed point number with 2 decimals:

Өөрчлөгчийг хоёр цэгийн `:` араас форматын төрлийг нэмэх замаар оруулдаг бөгөөд `.2f` энэ нь 2 аравтын бутархайтай тогтмол цэгийн дугаар гэсэн үг юм.

#### Example – Жишээ

Display the price with 2 decimals:

Үнийг 2 аравтын бутархайгаар харуулах:

`price = 59txt = f"The price is {price:.2f} dollars"print(txt)`

You can also format a value directly without keeping it in a variable:

Мөн утгыг хувьсагчид хадгалахгүйгээр шууд форматлаж болно:

#### Example – Жишээ

Display the value `95` with 2 decimals:

`95` утгыг 2 аравтын бутархайгаар харуулах:

`txt = f"The price is {95:.2f} dollars"print(txt)`

## Perform Operations in F-Strings – F-Strings дээр үйлдлүүдийг гүйцэтгэх

You can perform Python operations inside the placeholders.

Орлуулагч дотор Python үйлдлүүдийг хийж болно.

You can do math operations:

Та математикийн үйлдлүүдийг хийж болно:

#### Example – Жишээ

Perform a math operation in the placeholder, and return the result:

Орлуулагч дээр математикийн үйлдлийг хийж, үр дүнг буцаана:

`txt = f"The price is {20 * 59} dollars"print(txt)`

You can perform math operations on variables:

Та хувьсагч дээр математикийн үйлдлүүдийг хийж болно:

#### Example – Жишээ

Add taxes before displaying the price:

Үнийг харуулахын өмнө татвар нэмэх:

`price = 59tax = 0.25txt = f"The price is {price + (price * tax)} dollars"print(txt)`

You can perform `if...else` statements inside the placeholders:

Орлуулагчийн дотор `if...else` мэдэгдэл хийж болно:

##### Example – Жишээ

Return “Expensive” if the price is over 50, otherwise return “Cheap”:

Үнэ 50-аас дээш байвал “Үнэтэй” гэж буцаана, үгүй ​​бол “Хямд” гэж буцаана:

`price = 49txt = f"It is very {'Үнэтэй' if price>50 else 'Хямд'}"print(txt)`

## Execute Functions in F-Strings – F-string дотрох функцуудыг гүйцэтгэх

You can execute functions inside the placeholder:

Орлуулагч дотор функц гүйцэтгэх боломжтой:

#### Example – Жишээ

Use the string method `upper()`to convert a value into upper case letters:

Тэмдэгт мөрын аргыг ашиглан үгийг том үсгээр бичих:

`fruit = "apples"txt = f"I love {fruit.upper()}"print(txt)`

The function does not have to be a built-in Python method, you can create your own functions and use them:

Функц нь Python-нь арга байх албагүй бөгөөд та өөрийн функцүүдийг үүсгэж, тэдгээрийг ашиглаж болно:

#### Example – Жишээ

Create a function that converts feet into meters:

Фийтээс метр лүү хөрвүүлэх функц үүсгэнэ үү:

`def myconverter(x):  return x * 0.3048txt = f"The plane is flying at a {myconverter(30000)} meter altitude"print(txt)`

## More Modifiers – Илүү олон хувиргагч

At the beginning of this chapter we explained how to use the `.2f` modifier to format a number into a fixed point number with 2 decimals.

Энэ бүлгийн эхэнд бид `.2f`тоог 2 аравтын бутархайтай болгон хэлбэржүүлэхийн тулд хувиргагчийг хэрхэн ашиглах талаар тайлбарласан.

There are several other modifiers that can be used to format values:

Утгыг форматлахад ашиглаж болох өөр хэд хэдэн өөрчлөгч байдаг:

#### Example – Жишээ

Use a comma as a thousand separator:

Мянгатаар тусгаарлагч таслалыг ашигла:

`price = 59000txt = f"The price is {price:,} dollars"print(txt)`

Here is a list of all the formatting types. – 

Бүх форматын төрлүүдийн жагсаалт.

| Formatting Types Форматын Төрлүүд |  |  |
| --- | --- | --- |
| `:<` |   | Left aligns the result (within the available space) Үр дүнг зүүн талд нь байрлуулна (боломжтой зай дотор). |
| `:>` |   | Right aligns the result (within the available space) Үр дүнг баруун талд нь байрлуулна (боломжтой зай дотор). |
| `:^` |   | Center aligns the result (within the available space) Үр дүнг төвд нь байрлуулна (боломжтой зай дотор). |
| `:=` |   | Places the sign to the left most position Тэмдэгтийг хамгийн зүүн талд байрлуулна. |
| `:+` |   | Use a plus sign to indicate if the result is positive or negative Үр дүн эерэг эсвэл сөрөг байгааг тэмдэглэхийн тулд нэмэх тэмдэг ашиглана. |
| `:-` |   | Use a minus sign for negative values only Сөрөг утгуудын хувьд зөвхөн хасах тэмдэг ашиглана. |
| `: ` |   | Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers) Эерэг тоонуудын өмнө нэмэлт зай (болон сөрөг тоонуудын өмнө хасах тэмдэг) оруулна. |
| `:,` |   | Use a comma as a thousand separator Мянгатын ялгагчийн хувьд таслал ашиглана. |
| `:_` |   | Use a underscore as a thousand separator Мянгатын ялгагчийн хувьд доогуур зураас ашиглана. |
| `:b` |   | Binary format Бинар формат. |
| `:c` |   | Converts the value into the corresponding Unicode character Утгыг Unicode тэмдэгт болгон хөрвүүлнэ |
| `:d` |   | Decimal format Аравтын формат. |
| `:e` |   | Scientific format, with a lower case e Шинжлэх ухааны формат, жижиг `e`-тэй. |
| `:E` |   | Scientific format, with an upper case E Шинжлэх ухааны формат, том `E`-тэй. |
| `:f` |   | Fix point number format Тогтсон цэгийн тооны формат. |
| `:F` |   | Fix point number format, in uppercase format (show `inf` and `nan` as `INF` and `NAN`) Тогтсон цэгийн тооны формат, том үсгээр (inf болон nan-г INF болон NAN гэж харуулна). |
| `:g` |   | General format Ерөнхий формат. |
| `:G` |   | General format (using a upper case E for scientific notations) Ерөнхий формат (шинжлэх ухааны тэмдэглэгээнд том үсэг E-г ашиглана). |
| `:o` |   | Octal format Наймантын формат. |
| `:x` |   | Hex format, lower case Арван зургаатын формат, жижиг үсэг. |
| `:X` |   | Hex format, upper case Арван зургаатын формат, том үсэг. |
| `:n` |   | Number format Тооны формат. |
| `:%` |   | Percentage format Хувийн формат. |

## String format() – **Мөр форматлах**

Before Python 3.6 we used the `format()` method to format strings.

Python 3.6-аас өмнө бид `format()`мөрүүдийг форматлах аргыг ашигладаг байсан.

The `format()` method can still be used, but f-strings are faster and the preferred way to format strings.

`format()` аргыг ашиглах боломжтой хэвээр байгаа ч, f-string нь илүү хурдан бөгөөд мөрийг форматлах хамгийн тохиромжтой арга юм.

The next examples in this page demonstrates how to format strings with the `format()` method.

Дараагийн жишээнүүдэд `format()` аргаар мөрүүдийг хэрхэн форматлахыг харуулна.

The `format()` method also uses curly brackets as placeholders `{}`, but the syntax is slightly different:

`format()` арга нь бас хээтэй хаалтуудыг `{}` орлуулагч болгон ашигладаг боловч синтакс нь бага зэрэг өөр байна:

##### Example – Жишээ

Add a placeholder where you want to display the price:

Үнийг харуулах орлуулагчийг нэмнэ үү:

`price = 49txt = "The price is {} dollars"print(txt.format(price))`

You can add parameters inside the curly brackets to specify how to convert the value:

Та утгыг хэрхэн хөрвүүлэхийг зааж өгөхийн тулд буржгар хаалтанд параметрүүдийг нэмж болно:

#### Example – Жишээ

Format the price to be displayed as a number with two decimals:

Үнийг хоёр аравтын бутархайтай тоо хэлбэрээр харуулах:

`txt = "The price is {:.2f} dollars"`

## Multiple Values – Олон утга

If you want to use more values, just add more values to the format() method:

Хэрэв илүү их утгыг ашиглахыг хүсвэл format() аргад илүү олон утгыг нэмнэ үү:

`print(txt.format(price, itemno, count))`

And add more placeholders:

Бас илүү олон орлуулагч нэмнэ үү:

#### Example – Жишээ

`quantity = 3itemno = 567price = 49myorder = "I want {} pieces of item number {} for {:.2f} dollars."print(myorder.format(quantity, itemno, price))`

## Index Numbers – Индекс тоо

You can use index numbers (a number inside the curly brackets `{0}`) to be sure the values are placed in the correct placeholders:

Утгууд зөв орлуулагчид байрласан эсэхийг шалгахын тулд индексийн дугааруудыг (буржгар хаалт доторх тоо `{0}`) ашиглаж болно :

##### Example – Жишээ

`quantity = 3itemno = 567price = 49myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."print(myorder.format(quantity, itemno, price))`

Also, if you want to refer to the same value more than once, use the index number:

Түүнчлэн, хэрэв та ижил утгыг нэгээс олон удаа ашиглахыг хүсвэл индексийн дугаарыг ашиглана уу:

#### Example – Жишээ

`age = 36name = "John"txt = "His name is {1}. {1} is {0} years old."print(txt.format(age, name))`

## Named Indexes – Нэрлэсэн индексүүд

You can also use named indexes by entering a name inside the curly brackets `{carname}`, but then you must use names when you pass the parameter values `txt.format(carname = "Ford")`:

Мөн та буржгар хаалтанд нэр оруулах замаар индексүүдийг нэрлэн ашиглаж болох `{carname}`боловч дараа нь параметрийн утгыг дамжуулахдаа нэрийг ашиглах ёстой `txt.format(carname = "Ford")` болно:

#### Example – Жишээ

`myorder = "I have a {carname}, it is a {model}."print(myorder.format(carname = "Ford", model = "Mustang"))`

        [https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-string-formatting%2F&linkname=Python%C2%A0String%20Formatting](https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-string-formatting%2F&linkname=Python%C2%A0String%20Formatting)[https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-string-formatting%2F&linkname=Python%C2%A0String%20Formatting](https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-string-formatting%2F&linkname=Python%C2%A0String%20Formatting)[https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-string-formatting%2F&linkname=Python%C2%A0String%20Formatting](https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-string-formatting%2F&linkname=Python%C2%A0String%20Formatting)[https://www.addtoany.com/share](https://www.addtoany.com/share)
