String (satr) - bu Pythonda matn ma'lumotlarini saqlash uchun ishlatiladigan ma'lumot turi. String bir yoki bir nechta belgilardan iborat bo'lishi mumkin va ular ' ' yoki " " qo'shtirnoq ichida yoziladi.
# String yaratish name = "Nazarbek" greeting = 'Salom, dunyo!' multiline = '''Bu ko'p qatorli string misoli''' print(name) # Output: Nazarbek
Pythonda stringlar immutable (o'zgarmas) hisoblanadi. Bu shuni anglatadiki, string yaratilgandan so'ng uni o'zgartirish mumkin emas. Har bir belgi o'z indeksiga ega va 0 dan boshlanadi.
text = "Python" # Indeks orqali kirish print(text[0]) # Output: P print(text[-1]) # Output: n # Slicing (kesish) print(text[0:3]) # Output: Pyt print(text[2:]) # Output: thon
Python stringlar bilan ishlash uchun ko'plab foydali metodlarni taqdim etadi. Quyida eng ko'p ishlatiladigan metodlar keltirilgan:
text = "salom dunyo" result = text.upper() print(result) # Output: SALOM DUNYO
text = "SALOM DUNYO" result = text.lower() print(result) # Output: salom dunyo
text = "python dasturlash tili" result = text.capitalize() print(result) # Output: Python dasturlash tili
text = "salom dunyo" result = text.title() print(result) # Output: Salom Dunyo
text = " salom dunyo " result = text.strip() print(result) # Output: salom dunyo
text = "Men Python o'rganaman" result = text.replace("Python", "JavaScript") print(result) # Output: Men JavaScript o'rganaman
text = "olma,banan,uzum" fruits = text.split(",") print(fruits) # Output: ['olma', 'banan', 'uzum']
text = "Salom, Python!" index = text.find("Python") print(index) # Output: 7
text = "salom dunyo" result = text.count("o") print(result) # Output: 2
text = "salom dunyo" result = text.startswith("salom") print(result) # Output: True
text = "salom dunyo" result = text.endswith("dunyo") print(result) # Output: True
text = "salom dunyo" result = len(text) print(result) # Output: 11