ლექცია 07 · VII კვირაLecture 07 · Week VII

სტრიქონებიStrings

სტრიქონებთან სამუშაო ფუნქციები · ფორმატირება · ძებნა და ჩანაცვლება String methods · formatting · searching and replacing

⚠ შემდეგ კვირას — შუალედური გამოცდა ⚠ Next week — the midterm exam

გამეორება · ლექციები 05–06Review · lectures 05–06

შემოწმება — 9 კითხვაCheck yourself — 9 questions

1. რა განსხვავებაა return-სა და print-ს შორის ფუნქციაში? 1. What is the difference between return and print in a function?
return აბრუნებს მნიშვნელობას გამომძახებელს — მისი შემდგომი გამოყენება შეიძლება. print მხოლოდ ეკრანზე გამოაქვს; ასეთი ფუნქცია None-ს აბრუნებს. return hands a value back to the caller, so it can be used further. print only writes to the screen; such a function returns None.
2. რას აბრუნებს ფუნქცია, რომელსაც return არ აქვს? 2. What does a function without a return return?
None.None.
3. რატომ არის def f(a=1, b): შეცდომა? 3. Why is def f(a=1, b): an error?
ნაგულისხმევი მნიშვნელობის მქონე პარამეტრი ბოლოში უნდა იდგეს. სწორია def f(b, a=1):. A parameter with a default must come last. The correct form is def f(b, a=1):.
4. რას აკეთებს *args და რას **kwargs? 4. What do *args and **kwargs do?
*args აგროვებს პოზიციურ არგუმენტებს tuple-ად; **kwargsსახელდებულს ლექსიკონად. *args collects positional arguments into a tuple; **kwargs collects keyword arguments into a dictionary.
5. რას დაბეჭდავს?
x = 10
def f(): x = 5
f(); print(x)
5. What does this print?
x = 10
def f(): x = 5
f(); print(x)
10. ფუნქციაში შექმნილი x ლოკალურია — გლობალურს არ ცვლის. 10. The x created inside the function is local — it does not touch the global one.
6. math.sqrt(16) აბრუნებს 4-ს თუ 4.0-ს? 6. Does math.sqrt(16) return 4 or 4.0?
4.0math-ის ფუნქციები float-ს აბრუნებენ. 4.0 — the math functions return floats.
7. რომელი დიაპაზონიდან აბრუნებს რიცხვს random.randint(1, 6)? 7. What range does random.randint(1, 6) draw from?
1-დან 6-ის ჩათვლით — ორივე კიდე შედის, range-ისგან განსხვავებით. 1 to 6 inclusive — both ends are included, unlike range.
8. რას აკეთებს random.seed(42)? 8. What does random.seed(42) do?
აფიქსირებს გენერატორის საწყის წერტილს — მიმდევრობა განმეორებადი ხდება. სასარგებლოა ტესტირებისთვის. It fixes the generator’s starting point, making the sequence reproducible. Useful for testing.
9. რას აბრუნებს def f(): return 1, 2 და რა ტიპისაა? 9. What does def f(): return 1, 2 return, and of what type?
(1, 2) — ერთი ობიექტი, tuple. შეიძლება დაიშალოს: a, b = f(). (1, 2) — a single object, a tuple. It can be unpacked: a, b = f().

საფუძველიFundamentals

სტრიქონის შექმნაCreating strings

a = "ორმაგ ბრჭყალებში"
b = 'ერთმაგ ბრჭყალებში'
c = """მრავალხაზიანი
ტექსტი"""

# when the text itself contains quotes
d = "მან თქვა: 'გამარჯობა'"
e = 'ის არის "სტუდენტი"'
f = "ეკრანირება: \"ბრჭყალი\" ტექსტში"

სპეციალური სიმბოლოებიEscape sequences

ჩანაწერიWritten as რას ნიშნავსMeaning
\nახალი ხაზიNew line
\tტაბულაციაTab
\\უკუსლეშიBackslash
\" \'ბრჭყალი ტექსტშიA quote inside the text
print("გზა: C:\\Users\\K")
print(r"გზა: C:\Users\K")     # r — a "raw" string

წვდომაAccess

ინდექსაცია — სიმბოლო ნომრითIndexing — a character by position

s = "Python"
#    0 1 2 3 4 5
#   -6-5-4-3-2-1

print(s[0])      # P   the first
print(s[5])      # n   the last
print(s[-1])     # n   the last, shorter
print(s[-2])     # o   one before the last
print(len(s))    # 6

print(s[10])
# IndexError: string index out of range
ინდექსი 0-დან იწყებაბოლო სიმბოლოს ინდექსია len(s) - 1, ან უბრალოდ -1. Indexing starts at 0The last character is at len(s) - 1, or simply -1.
უარყოფითი ინდექსიითვლის ბოლოდან. s[-1] ბევრად კითხვადია, ვიდრე s[len(s)-1]. Negative indexescount from the end. s[-1] reads far better than s[len(s)-1].

წვდომაAccess

ამონაჭერი (slice) — [start:stop:step]Slicing — [start:stop:step]

s = "პროგრამირება"

print(s[0:5])     # პროგრ   — 5 is excluded
print(s[:5])      # პროგრ   — from the start
print(s[5:])      # ამირება — to the end
print(s[:])       # a full copy
print(s[-4:])     # რება    — the last 4
print(s[::2])     # every second character
print(s[::-1])    # reversed!
ისევ იგივე წესიstop არ შედის — ზუსტად ისე, როგორც range()-ში. The same rule againstop is excluded — exactly as in range().
ხერხი, რომელიც უნდა იცოდეs[::-1] — სტრიქონის შებრუნების უმოკლესი გზა. პალინდრომის შემოწმებისთვის აუცილებელია. A trick worth knowings[::-1] is the shortest way to reverse a string — essential for palindrome checks.
დაფაზე დახატე ინდექსების ორი რიგი (დადებითი და უარყოფითი). სლაისინგი ვიზუალურად ბევრად ადვილად ესმით. Draw both index rows on the board (positive and negative). Slicing lands much better visually.

მნიშვნელოვანი თვისებაAn important property

სტრიქონი უცვლელია (immutable)Strings are immutable

s = "Python"

s[0] = "J"
# TypeError: 'str' object does not support item assignment

# the right way — build a new string
s2 = "J" + s[1:]
print(s2)         # Jython
print(s)          # Python — the original is unchanged
ყველა მეთოდი ახალ სტრიქონს აბრუნებს Every method returns a new string
name = "ნინო"
name.upper()          # the result is thrown away!
print(name)           # ნინო

name = name.upper()   # correct
print(name)           # ნინო (Georgian has no letter case)

სიები (X კვირა), პირიქით, ცვალებადია — ეს განსხვავება მნიშვნელოვანია. Lists (week X), by contrast, are mutable — that difference matters.

მეთოდებიMethods

რეგისტრი და გასუფთავებაCase and trimming

s = "python IS fun"

print(s.upper())       # PYTHON IS FUN
print(s.lower())       # python is fun
print(s.title())       # Python Is Fun
print(s.capitalize())  # Python is fun
print(s.swapcase())    # PYTHON is FUN
s = "   ტექსტი   "

print(s.strip())       # "ტექსტი"
print(s.lstrip())      # "ტექსტი   "
print(s.rstrip())      # "   ტექსტი"

f = "###სათაური###"
print(f.strip("#"))    # "სათაური"
strip() — თითქმის ყოველთვის საჭიროაinput()-ით მიღებულ ტექსტში ხშირად ზედმეტი ჰარეებია. input().strip() კარგი ჩვევაა. strip() — you almost always want itText from input() often carries stray spaces. input().strip() is a good habit.

მეთოდებიMethods

ძებნაSearching

s = "პროგრამირება არის საინტერესო"

print("არის" in s)            # True   — the simplest check
print("java" not in s)        # True

print(s.find("არის"))         # 13     — the index
print(s.find("java"))         # -1     — not found
print(s.index("არის"))        # 13
# s.index("java")             # ValueError!

print(s.count("რ"))           # how many times it occurs
print(s.startswith("პრო"))    # True
print(s.endswith("ო"))        # True
find თუ index?find ვერ პოვნისას აბრუნებს -1-ს, index კი შეცდომას აგდებს. თუ არსებობა დარწმუნებული არ ხარ — find ან in. find or index?find returns -1 when nothing is found; index raises an error. If you are not sure it is there, use find or in.

მეთოდებიMethods

ჩანაცვლება, დაშლა, შეერთებაReplacing, splitting, joining

s = "მე ვსწავლობ Java-ს"
print(s.replace("Java", "Python"))
print("aaa".replace("a", "b", 2))      # bba — only 2

# split — string → list
line = "ნინო,გიორგი,ანა"
names = line.split(",")
print(names)                # ['ნინო', 'გიორგი', 'ანა']

text = "ერთი ორი სამი"
print(text.split())         # on whitespace, automatically

# join — list → string
print(", ".join(names))     # ნინო, გიორგი, ანა
print("-".join("abc"))      # a-b-c
split() + join()ესაა ტექსტური მონაცემების დამუშავების საფუძველი — CSV ფაილები, მომხმარებლის შეყვანა, ლოგები. ფაილებთან მუშაობისას (IX კვირა) მუდმივად გამოვიყენებთ. split() + join()The foundation of text processing — CSV files, user input, log files. We will use them constantly once we reach files (week IX).

მეთოდებიMethods

შემოწმება — რა შეიცავს სტრიქონიChecking what a string contains

print("12345".isdigit())      # True   digits only
print("abc".isalpha())        # True   letters only
print("abc123".isalnum())     # True   letters or digits
print("   ".isspace())        # True   whitespace only
print("Hello".istitle())      # True
print("ABC".isupper())        # True

პრაქტიკული გამოყენებაIn practice

value = input("შეიყვანე რიცხვი: ").strip()

if value.isdigit():
    number = int(value)
    print("კვადრატი:", number ** 2)
else:
    print("ეს რიცხვი არ არის")
ყურადღება"-5".isdigit() და "3.14".isdigit() ორივე False-ია — მინუსი და წერტილი ციფრები არაა. სრულყოფილი შემოწმებისთვის try/except-ია საჭირო (XII კვირა). CarefulBoth "-5".isdigit() and "3.14".isdigit() are False — a minus sign and a dot are not digits. A complete check needs try/except (week XII).

ფორმატირებაFormatting

f-სტრიქონის სრული შესაძლებლობებიThe full power of f-strings

name = "ნინო"
score = 87.6543
n = 42

print(f"{name} — {score:.2f}")        # ნინო — 87.65
print(f"{score:10.2f}")               # "     87.65"  width 10
print(f"{name:>12}")                  # right aligned
print(f"{name:<12}|")                 # left aligned
print(f"{name:^12}|")                 # centred
print(f"{name:*^12}")                 # ****ნინო****

print(f"{n:05}")                      # 00042
print(f"{1234567:,}")                 # 1,234,567
print(f"{0.256:.1%}")                 # 25.6%
print(f"{255:b} {255:o} {255:x}")     # 11111111 377 ff

print(f"{n = }")                      # n = 42  (for debugging)
ცხრილის დაბეჭდვაf"{name:<15}{score:>8.2f}" — გასწორებული სვეტები ყოველგვარი ბიბლიოთეკის გარეშე. Printing a tablef"{name:<15}{score:>8.2f}" — aligned columns without any library at all.

პრაქტიკაPractice

სტრიქონზე ციკლით გავლაLooping over a string

text = input("ტექსტი: ").lower()
vowels = "აეიოუ"
count = 0

for ch in text:
    if ch in vowels:
        count += 1

print("ხმოვნები:", count)
word = input("სიტყვა: ").lower().strip()
clean = ""

for ch in word:
    if ch.isalnum():
        clean += ch

if clean == clean[::-1]:
    print("პალინდრომია")
else:
    print("არაა პალინდრომი")
for i, ch in enumerate("Python"):
    print(i, ch)
enumerate()ერთდროულად გაძლევს ინდექსსაც და მნიშვნელობასაც. range(len(s))-ზე ბევრად კითხვადია. enumerate()gives you the index and the value at once. Far more readable than range(len(s)).

სრული მაგალითიFull example

ტექსტის ანალიზატორიA text analyser

def analyze(text):
    """ტექსტის მოკლე სტატისტიკა. / Quick text statistics."""
    words = text.split()
    letters = sum(1 for ch in text if ch.isalpha())

    print(f"{'სიმბოლოები:':<20}{len(text):>6}")
    print(f"{'ასოები:':<20}{letters:>6}")
    print(f"{'სიტყვები:':<20}{len(words):>6}")
    print(f"{'წინადადებები:':<20}{text.count('.'):>6}")

    if words:
        longest = max(words, key=len)
        print(f"{'ყველაზე გრძელი:':<20}{longest:>6}")


sample = input("ჩასვი ტექსტი: ")
analyze(sample)
ეს კარგი „ხიდია“ ფუნქციებსა და სტრიქონებს შორის. სთხოვე დაამატონ: საშუალო სიტყვის სიგრძე, ყველაზე ხშირი ასო (ეს უკვე ლექსიკონს მოითხოვს — კაუჭი XI კვირისთვის). A good bridge between functions and strings. Ask them to add: average word length, most frequent letter (that already needs a dictionary — a hook for week XI).

მომზადებაPreparation

შუალედური გამოცდა — VIII კვირაThe midterm exam — week VIII

ფორმატი — 30 ქულაFormat — 30 points

  • 10 ტესტური კითხვა × 1 ქულა
  • 10 ღია კითხვა × 2 ქულა
  • 10 test questions × 1 point
  • 10 open questions × 2 points
ყურადღებაბევრ პროგრამაში შუალედურზე მინიმალური ზღვრის ვერგადალახვა დასკვნით გამოცდაზე დაშვებას გიკეტავს — ზუსტი წესი შენს კურსში დააზუსტე. CarefulIn many programmes, failing to clear the midterm threshold blocks you from the final exam — check the exact rule for your own course.

რა შედისWhat it covers

  • I–VII კვირის მთელი მასალა
  • სინტაქსი, ტიპები, ოპერატორები
  • პირობები და ციკლები
  • ჩაშენებული ფუნქციები, math, random
  • საკუთარი ფუნქციები
  • სტრიქონები და მათი მეთოდები
  • Everything from weeks I–VII
  • Syntax, types, operators
  • Conditions and loops
  • Built-in functions, math, random
  • Writing your own functions
  • Strings and their methods
როგორ მოემზადოგაიარე ყოველი ლექციის „შემაჯამებელი“ სლაიდი და გამეორების კითხვები (ლექციები 03, 05, 07). ხელახლა დაწერე — არა წაიკითხო — 3 პრაქტიკული დავალება. How to prepareGo through the wrap-up slide of every lecture and the review questions (lectures 03, 05, 07). Re-write — do not just re-read — three of the practical assignments.

შემაჯამებელიWrap-up

რა უნდა დაგამახსოვრდესWhat to remember

სახლში1) სიტყვების დათვლა და ყველაზე გრძელის პოვნა. 2) CSV-ხაზის დაშლა და ლამაზად დაბეჭდვა. 3) ცეზარის შიფრი (ასოს გადაწევა). 4) სახელისა და გვარის ინიციალები. At home1) Count the words and find the longest one. 2) Split a CSV line and print it neatly. 3) A Caesar cipher (shifting letters). 4) Initials from a first and last name.
შემდეგი — VIII კვირა: შუალედური გამოცდალექცია 08 — გამეორების სრული დეკი მოსამზადებლად. Next — week VIII: the midtermLecture 08 is a full revision deck to prepare with.