Python Strings

Агуулга

Python Strings – Python дахь Мөрүүд #

Strings – Мөрүүд #

Strings in python are surrounded by either single quotation marks, or double quotation marks.

Python дахь тэмдэгт мөрүүд нь нэг хашилт, эсвэл давхар хашилт байна.

‘hello’ is the same as “hello”.

‘hello’ нь “hello”-тай адилхан.

You can display a string literal with the print() function:

print() функц ашиглан тэмдэгт мөрийг дэлгэц дээр харуулж болно:

Example – Жишээ #

print("Hello")
print('Hello')

Assign String to a Variable – Тэмдэгт мөрийг хувьсагчид оноох #

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

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

Example – Жишээ #

a = "Hello"
print(a)

Multiline Strings – Олон мөртэй тэмдэгт мөр #

You can assign a multiline string to a variable by using three quotes:

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

Example – Жишээ #

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

Эсвэл гурван ганц хаалтаар:

Example – Жишээ #

a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Note: in the result, the line breaks are inserted at the same position as in the code.

Анхаар: үр дүнд, мөрөөр хуваасан код бичигдсэн байршлаараа орно.

Strings are Arrays – Тэмдэгт мөр нь массивууд юм #

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

Python-д олон алдартай програмчлалын хэл шиг, тэмдэгт мөрүүд нь unicode тэмдэгтүүдийг илэрхийлсэн байтын массивууд юм.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Гэхдээ, Python-д тэмдэгтэд өгөгдлийн төрөл байхгүй, нэг тэмдэгт нь 1 тэмдэгт мөр юм.

Square brackets can be used to access elements of the string.

Дөрвөлжин хаалт ашиглан тэмдэгт мөрийн элементүүдэд хандаж болно.

Example – Жишээ #

Get the character at position 1 (remember that the first character has the position 0):

1 дүгээр байрлалд байх тэмдэгтийг харах(үүнийг санаж байгаарай, эхний тэмдэгт 0-ээр байрлал юм):

a = "Hello, World!"
print(a[1])

Looping Through a String – Тэмдэгт мөрийг Дуустал нь Гүйлгэх #

Since strings are arrays, we can loop through the characters in a string, with a for loop.

Тэмдэгт мөрүүд нь массив учраас, бид for давталтыг ашиглан тэмдэгт мөрийн тэмдэгтүүдийг гүйлгэж болно.

Example – Жишээ #

Loop through the letters in the word “banana”:

“banana” гэх үгийг үсгүүдийг гүйлгэж харах:

for x in "banana":
  print(x)

Learn more about For Loops in Python For Loops chapter.

For давталтын талаар илүү ихийг мэдэхийн тулд Python For Loops бүлгийг үзнэ үү.

String Length – Тэмдэгт мөрийн урт #

To get the length of a string, use the len() function.

Тэмдэгт мөрийн уртыг авахын тулд len() функцийг ашиглана.

Example – Жишээ #

The len() function returns the length of a string:

len() функц нь тэмдэгт мөрийн тэмдэгтийн тоог буцаана:

a = "Hello, World!"
print(len(a))

Check String – Тэмдэгт мөр шалгах #

To check if a certain phrase or character is present in a string, we can use the keyword in.

Тэмдэгт мөр нь тодорхой үг эсвэл тэмдэгт байгаа эсэхийг шалгахын тулд in түлхүүр үгийг ашиглана.

Example – Жишээ #

Check if “free” is present in the following text:

Дараах текстэнд “free” байгаа эсэхийг шалгана уу:

txt = "The best things in life are free!"
print("free" in txt)

Learn more about If statements in Python If…Else chapter.

If нөхцөлүүдийн талаар илүү ихийг Python If…Else бүлгээс мэдэж аваарай.

Check if NOT – Байхгүй байна уу гэж шалгах #

To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

Тэмдэгт мөрөнд тодорхой үг эсвэл тэмдэгт байхгүй эсэхийг шалгахын тулд not in түлхүүр үгийг ашиглана.

Example – Жишээ #

Check if “expensive” is NOT present in the following text:

Доорх текстэд “expensive” гэсэн үг байхгүй байна уу гэж шалгана:

txt = "The best things in life are free!"
print("expensive" not in txt)

Use it in an if statement:

If нөхцөлд ашиглана:

Example – Жишээ #

print only if “expensive” is NOT present:

Зөвхөн “expensive” гэсэн үг байхгүй тохиолдолд гаргаж үзүүлнэ:

txt = "The best things in life are free!"
if "expensive" not in txt:
  print("No, 'expensive' is NOT present.")

Python – Slicing Strings – Python – Тэмдэгт мөрийг хэсэгчлэх (Slicing Strings) #

Slicing – Хэсэгчлэх #

You can return a range of characters by using the slice syntax.

Та зүсэх синтакс ашиглан тэмдэгт мөрийн хэсгийг буцааж болно.

Specify the start index and the end index, separated by a colon, to return a part of the string.

Эхлэх индекс болон төгсгөлийн индексийг цэгээр тусгаарлан, тэмдэгт мөрийн нэг хэсгийг буцаана.

Example – Жишээ #

Get the characters from position 2 to position 5 (not included):

2 дох байрлалаас 5 дах(орохгүй) байрлал хүртэл байх тэмдэгүүдийг сонгож харах:

b = "Hello, World!"
print(b[2:5])

Note: The first character has index 0.

Тайлбар: Эхний тэмдэгт нь 0-р индекс байна.

Slice From the Start – Эхэллээс зүсэх #

By leaving out the start index, the range will start at the first character:

Эхлэх индексийг орхисноор, эхний тэмдэгтээс эхэлнэ:

Example – Жишээ #

Get the characters from the start to position 5 (not included):

Эхнээс нь 5 дах(орохгүй) байрлал хүртэл байх тэмдэгүүдийг сонгож харах:

b = "Hello, World!"
print(b[:5])

Slice To the End – Төгсгөл хүртэл зүсэх  #

By leaving out the end index, the range will go to the end:

Төгсгөлийн индексийг орхисноор, төгсгөл хүртэл явах болно:

Example – Жишээ #

Get the characters from position 2, and all the way to the end:

2 дох байрлалаас дуусах хүртэл байх тэмдэгүүдийг сонгож харах:

b = "Hello, World!"
print(b[2:])

Negative Indexing – Сөрөг индекстэй зүсэх #

Use negative indexes to start the slice from the end of the string:

Тэмдэгт мөрийн төгсгөлөөс зүсэлт эхлүүлэхийн тулд сөрөг индексийг ашиглана:

Example – Жишээ #

Get the characters from position 2 to position 5 (not included):

2 дох байрлалаас 5 дах(орохгүй) байрлал хүртэл байх тэмдэгүүдийг сонгож харах:

b = "Hello, World!"
print(b[-5:-2])

Python – Modify Strings – Тэмдэгт мөрийг өөрчлөх #

Python has a set of built-in methods that you can use on strings.

Python-д тэмдэгт мөрүүдийг өөрчлөхөд ашиглаж болох оруулсан аргуудын багц байдаг.

Upper Case – Том үсгээр бичих #

Example – Жишээ #

The upper() method returns the string in upper case:

upper() арга нь тэмдэгт мөрийг том үсгээр буцаана:

a = "Hello, World!"
print(a.upper())

Lower Case – Жижиг үсгээр бичих #

Example – Жишээ #

The lower() method returns the string in lower case:

lower() арга нь тэмдэгт мөрийг жижиг үсгээр буцаана:

a = "Hello, World!"
print(a.lower())

Remove Whitespace – Хоосон зайг арилгах #

Whitespace is the space before and/or after the actual text, and very often you want to remove this space.

Хоосон зай гэдэг нь бодит текстийн өмнөх болон/эсвэл дараах орон зай бөгөөд маш олон тохиолдолд энэ орон зайг арилгахыг хүсдэг.

Example – Жишээ #

The strip() method removes any whitespace from the beginning or the end:

strip() арга нь эхлэл болон төгсгөлийн аливаа хоосон зайг арилгана:

a = " Hello, World! "
print(a.strip()) # "Hello, World!" болно

Replace String – Тэмдэгт мөрийг орлуулах #

Example – Жишээ #

The replace() method replaces a string with another string:

replace() арга нь нэг тэмдэгт мөрийг өөр нэг тэмдэгт мөрөөр орлуулна:

a = "Hello, World!"
print(a.replace("H", "J"))

Split String – Тэмдэгт мөрийг хуваах #

The split() method returns a list where the text between the specified separator becomes the list items.

split() арга нь заагчийн хоорондох текстийг жагсаалтын зүйлс болгоно.

Example – Жишээ #

The split() method splits the string into substrings if it finds instances of the separator:

split() арга нь заагчийг олсон тохиолдолд тэмдэгт мөрийг дэд мөрүүдэд хуваана:

a = "Hello, World!"
print(a.split(",")) # ['Hello', ' World!'] болно

Learn more about Lists in Python Lists chapter.

Жагсаалтын талаар илүү ихийг Python Lists бүлгээс үзнэ үү.

String Methods – Тэмдэгт мөрийн аргууд #

Learn more about String Methods with String Methods Reference

Тэмдэгт мөрийн аргуудын талаар илүү ихийг Тэмдэгт Мөрийн Аргууд (String Methods) лавлахаас үзнэ үү.

Python – String Concatenation – Python – Тэмдэгт Мөрийн Нийлмэл #

String Concatenation – Тэмдэгт Мөрийг Нийлүүлэх #

To concatenate, or combine, two strings you can use the + operator.

Хоёр тэмдэгт мөрийг нийлүүлэхийн тулд + операторыг ашиглаж болно.

Example – Жишээ #

Merge variable a with variable b into variable c:

a хувьсагчийг b хувьсагчтай нийлүүлж, c хувьсагчид хадгалах:

a = "Hello"
b = "World"
c = a + b
print(c) # HelloWorld болно

Example – Жишээ #

To add a space between them, add a " ":

Тэдгээрийн хооронд зай нэмэхийн тулд " " нэмнэ:

a = "Hello"
b = "World"
c = a + " " + b
print(c) # Hello World болно

Python – Format – Strings – Python – Формат – Тэмдэгт Мөр #

String Format – Тэмдэгт Мөрийн Формат #

As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:

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

Example – Жишээ #

age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method!

Гэхдээ тэмдэгт мөрүүд болон тоонуудыг format() аргыг ашиглан нэгтгэж болно!

The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:

format() арга дамжуулсан аргументуудыг форматлаж, тэмдэгт мөрийн байрлал эзлэгчдэд {} оруулдаг:

 

Example – Жишээ #

Use the format() method to insert numbers into strings:

Тоо тэмдэгт мөрөнд оруулахын тулд format() аргыг ашиглана:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

The format() method takes unlimited number of arguments, and are placed into the respective placeholders:

format() арга хязгааргүй тооны аргументуудыг авдаг бөгөөд тус бүрийн байрлал эзлэгчдэд оруулдаг:

Example – Жишээ #

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:

Та индекс дугааруудыг {0} ашиглаж, аргументуудыг байрлалыг оруулж болно:

Example – Жишээ #

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Learn more about String Formatting in our String Formatting chapter.

Форматын талаар илүү ихийг String Formatting бүлгээс үзнэ үү.

Python – Escape Characters – Python – Дүрс тэмдэгүүд #

Escape Character – Дүрс Тэмдэг #

To insert characters that are illegal in a string, use an escape character.

Тэмдэгт мөрөнд хориглосон тэмдэгтүүдийг оруулахын тулд дүрс тэмдэг ашиглана.

An escape character is a backslash \ followed by the character you want to insert.

Дүрс тэмдэг нь \ дараа оруулахыг хүссэн тэмдэгтээр дараалагдана.

An example of an illegal character is a double quote inside a string that is surrounded by double quotes:

Хориглох тэмдэгтийн жишээ бол давхар хаалт тэмдэгт мөрийн дотор давхар ишлэл ашиглах юм.

Example – Жишээ #

You will get an error if you use double quotes inside a string that is surrounded by double quotes:

Давхар хаалтуудийг ашиглавал алдаа гарна:

txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

Энэ асуудлыг шийдэхийн тулд дүрс тэмдэг \ ашиглана:

Example – Жишээ #

The escape character allows you to use double quotes when you normally would not be allowed:

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

txt = "We are the so-called \"Vikings\" from the north."

Escape Characters – Дүрс тэмдэгүүд #

Other escape characters used in Python:

Python-д ашиглагддаг бусад дүрс тэмдэгүүд:

Code

Код

Result

Үр дүн

 
\’

Single Quote

Ганц хаалт

 
\\

Backslash

хойшоо налуу зураас

 
\n

New Line

Шинэ Мөр

 
\r

Carriage Return

Карригийн Буцаалт

 
\t

Tab

Таб

 
\b

Backspace

ухрах

 
\f

Form Feed

Хуудасны Таслал

 
\ooo

Octal value

Октал утга

 
\xhh

Hex value

Хекс утга

Python – String Methods – Python – Тэмдэгт Мөрийн Аргууд #

String Methods – Тэмдэгт Мөрийн Аргууд #

Python has a set of built-in methods that you can use on strings.

Python-д ашиглаж болох оруулсан аргуудын багц байдаг.

Note: All string methods return new values. They do not change the original string.

Тэмдэглэл: Бүх тэмдэгт мөрийн аргууд шинэ утгуудыг буцаана. Тэд анхны тэмдэгт мөрийг өөрчлөхгүй.

Method Description
capitalize()

Converts the first character to upper case

Эхний тэмдэгтийг том үсгээр хувиргана

casefold()

Converts string into lower case

Тэмдэгт мөрийг жижиг үсгээр хувиргана

center()

Returns a centered string

 Төвлөрсөн тэмдэгт мөрийг буцаана

count()

Returns the number of times a specified value occurs in a string

Тодорхой утга хэдэн удаа орж байгааг буцаана

encode()

Returns an encoded version of the string

Тэмдэгт мөрийн кодлогдсон хувилбарыг буцаана

endswith()

Returns true if the string ends with the specified value

Тэмдэгт мөр тодорхой утгаар төгсөж байгаа эсэхийг шалгана

expandtabs()

Sets the tab size of the string

Тэмдэгт мөрийн таб хэмжээг тохируулна

find()

Searches the string for a specified value and returns the position of where it was found

Тодорхой утгыг тэмдэгт мөрөөс хайж, олдсон байрлалыг буцаана

format()

Formats specified values in a string

Тодорхой утгуудыг тэмдэгт мөрөнд форматлана

format_map()

Formats specified values in a string

Тодорхой утгуудыг тэмдэгт мөрөнд форматлана

index()

Searches the string for a specified value and returns the position of where it was found

Тодорхой утгыг тэмдэгт мөрөөс хайж, олдсон байрлалыг буцаана

isalnum()

Returns True if all characters in the string are alphanumeric

Тэмдэгт мөрийн бүх тэмдэгтүүд нь үсэг-тоогоор тэмдэглэсэн эсэхийг шалгана

isalpha()

Returns True if all characters in the string are in the alphabet

Тэмдэгт мөрийн бүх тэмдэгтүүд нь цагаан толгой эсэхийг шалгана

isascii()

Returns True if all characters in the string are ascii characters

Тэмдэгт мөрийн бүх тэмдэгтүүд нь ASCII тэмдэгтүүд эсэхийг шалгана

isdecimal()

Returns True if all characters in the string are decimals

Тэмдэгт мөрийн бүх тэмдэгтүүд нь арвантын тэмдэгтүүд эсэхийг шалгана

isdigit()

Returns True if all characters in the string are digits

Тэмдэгт мөрийн бүх тэмдэгтүүд нь цифрүүд эсэхийг шалгана

isidentifier()

Returns True if the string is an identifier

Тэмдэгт мөр нь таних тэмдэгтэй эсэхийг шалгана

islower()

Returns True if all characters in the string are lower case

Тэмдэгт мөрийн бүх тэмдэгтүүд нь жижиг үсэг эсэхийг шалгана

isnumeric()

Returns True if all characters in the string are numeric

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

isprintable()

Returns True if all characters in the string are printable

Тэмдэгт мөрийн бүх тэмдэгтүүд нь хэвлэгдэх боломжтой эсэхийг шалгана

isspace()

Returns True if all characters in the string are whitespaces

Тэмдэгт мөрийн бүх тэмдэгтүүд нь зайтай эсэхийг шалгана

istitle()

Returns True if the string follows the rules of a title

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

isupper()

Returns True if all characters in the string are upper case

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

join()

Joins the elements of an iterable to the end of the string

Нэгтгэгдэх элементийн төгсгөлд тэмдэгт мөрийг нэмж нэгтгэнэ

ljust()

Returns a left justified version of the string

Зүүн талдаа тохирсон тэмдэгт мөрийг буцаана

lower()

Converts a string into lower case

Тэмдэгт мөрийг жижиг үсгээр хувиргана

lstrip()

Returns a left trim version of the string

Зүүн талаас тайрсан тэмдэгт мөрийг буцаана

maketrans()

Returns a translation table to be used in translations

Орчуулгад ашиглах орчуулгын хүснэгтийг буцаана

partition()

Returns a tuple where the string is parted into three parts

Тэмдэгт мөрийг гурван хэсэгт хуваасан жагсаалтыг буцаана

replace()

Returns a string where a specified value is replaced with a specified value

Тодорхой утгыг өөр нэг утгаар орлуулсан тэмдэгт мөрийг буцаана

rfind()

Searches the string for a specified value and returns the last position of where it was found

Тодорхой утгыг тэмдэгт мөрөөс хайж, хамгийн сүүлийн байрлалыг буцаана

rindex()

Searches the string for a specified value and returns the last position of where it was found

Тодорхой утгыг тэмдэгт мөрөөс хайж, хамгийн сүүлийн байрлалыг буцаана

rjust()

Returns a right justified version of the string

Баруун талдаа тохирсон тэмдэгт мөрийг буцаана

rpartition()

Returns a tuple where the string is parted into three parts

Тэмдэгт мөрийг гурван хэсэгт хуваасан жагсаалтыг буцаана

rsplit()

Splits the string at the specified separator, and returns a list

Тодорхой заагч дээр тэмдэгт мөрийг хувааж, жагсаалт буцаана

rstrip()

Returns a right trim version of the string

Баруун талаас тайрсан тэмдэгт мөрийг буцаана

split()

Splits the string at the specified separator, and returns a list

Тодорхой заагч дээр тэмдэгт мөрийг хувааж, жагсаалт буцаана

splitlines()

Splits the string at line breaks and returns a list

Мөрийн завсарлага дээр тэмдэгт мөрийг хувааж, жагсаалт буцаана

startswith()

Returns true if the string starts with the specified value

Тэмдэгт мөр тодорхой утгаар эхэлж байгаа эсэхийг шалгана

strip()

Returns a trimmed version of the string

Тайрсан тэмдэгт мөрийг буцаана

swapcase()

Swaps cases, lower case becomes upper case and vice versa

Том үсгийг жижиг үсэг болгож, эсрэгээр нь хувиргана

title()

Converts the first character of each word to upper case

Тэмдэгт мөрийн үг бүрийн эхний үсгийг том үсгээр хувиргана.

translate()

Returns a translated string

Орчуулсан тэмдэгт мөрийг буцаана.

upper()

Converts a string into upper case

Тэмдэгт мөрийг том үсгээр хувиргана.

zfill()

Fills the string with a specified number of 0 values at the beginning

Тэмдэгт мөрийн эхэнд тодорхой тооны 0 утгуудыг нэмнэ.

Powered by BetterDocs

Leave a Reply