ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ
String methods
Names typed into a form arrive messy: " hana ", "ABEL", a stray space at the end.
By the end of this lesson you'll clean text, split it into words, join words back
together, and search inside it, using the one rule that makes strings different from
lists.
Every lesson in this module works fully in your browser.
Strings don't change
repr() shows a string the way you'd type it in code, with its quotes, so you can see
every space. Predict what this prints.
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
name = " Hana "
name.strip()
print(repr(name))Python prints
' Hana '
name.strip() makes a new string without the spaces, but nothing gives it a name, so it's lost. name still refers to the original string.
If you said 'Hana', you used the rule from lesson 4.2: prices.sort() changes the
list. That rule is right for lists and wrong for strings.
strip() is a
,
like the list methods in lesson 4.2. But a string method never changes the string it's
called on. strip() does its work and returns a new string, the way vat(250)
returned a number in lesson 5.1. To keep the result, give it a name:
name = " Hana "
name = name.strip()
print(repr(name))In the editor, press Escape then Tab to move on.
Read line 2 as "name becomes what name.strip() returns". Step through the two
versions together: each arrow shows which value a name refers to.
Names and objects
Press Next to run one line at a time. Each arrow shows the object a name refers to.Each row is one step: the line that just ran, and the object each name refers to after it።
name refers to a str, ' Hana '.
Step 1 of 4
Step 1 of 4. Line 1: name = " Hana ". name now refers to a new str, ' Hana '.
| Step | Line | Names and objects |
|---|---|---|
| 1 | 1 |
|
| 2 | 2 |
|
| 3 | 3 |
|
| 4 | 4 |
|
On line 2 the new string is made and dropped at once, so the diagram never shows it. On
line 3, name moves to a new string, and no name refers to the old one anymore.
The two rules are mirror images:
sort, append (lesson 4.2) | strip, upper, replace | |
|---|---|---|
| Changes the value it's called on? | Yes | Never |
| Returns | None | A new string |
| Right | prices.sort() | name = name.strip() |
| Wrong | prices = prices.sort(): prices becomes None | name.strip() alone: nothing changes |
The reason is lesson 4.8: strings are
.
No method can change a string, so a method that makes different text has to hand you a
new string. (Methods that answer a question return other things: later in this lesson,
find returns a number and split a list.)
ጥያቄ
After s = "tea" and then s.upper(), what is s?
Changing case
lower(), upper(), and title() each return a new string with the letters changed.
title() makes the first letter of every word a capital and the rest small.
city = "adDIS abeba"
print(city.lower())
print(city.upper())
print(city.title())
print("ሰላም".upper())In the editor, press Escape then Tab to move on.
The last line is unchanged: Ge'ez has no capital and small letters, so there's nothing
for upper() to change. Case belongs to some scripts, like Latin, not all. Change
city to your own city, typed in mixed case, and run it again.
Because each method returns a string, you can call the next method on the result:
" hana ".strip().title() strips first, then capitalizes, and gives 'Hana'.
Splitting and joining
split() cuts a string into a list of words. Look closely at the two spaces between the
names, then predict both lines.
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
text = "Hana Abel"
print(text.split())
print(text.split(" "))Python prints
['Hana', 'Abel'] ['Hana', '', 'Abel']
With no argument, split() cuts at every run of spaces, however long. split(" ") cuts at each single space, so two spaces in a row leave an empty string between them.
The text you cut at is the
.
split(",") uses a comma, split(" ") exactly one space. To split words typed by a
person, use split() with nothing inside: it also ignores spaces at the ends.
join() does the opposite: it glues a list of strings into one string. It reads
backwards at first, because you call it on the separator:
names = ["Hana", "Abel", "Selam"]
print(", ".join(names))
print(" - ".join(names))In the editor, press Escape then Tab to move on.
join only takes strings. Try it on prices:
Searching inside a string
find() returns the index where some text starts, or -1 if it isn't there at all.
count() counts how many times it appears; like every search here, it's case-sensitive,
so the E in ETB isn't counted. replace() returns a new string with every match
replaced, not just the first:
sms = "You paid ETB 250 to Selam Coffee"
print(sms.find("ETB"))
print(sms.find("USD"))
print(sms.count("e"))
print("0911-23-45-67".replace("-", ""))In the editor, press Escape then Tab to move on.
Strings also have index(), which gives the same answer as find() when the text is
there. When it isn't:
startswith() checks the beginning. Give it a tuple and it checks each one. Ethiopian
mobile numbers start with 09 or 07:
print("0712345678".startswith(("09", "07")))
print("0112345678".startswith(("09", "07")))In the editor, press Escape then Tab to move on.
መልመጃ
Clean the sign-up list
People typed their names into a sign-up form. Strip the spaces, fix the case, and print all the names on one line, separated by a comma and a space.
Hana, Abel, Selam TesfayeYour code
typed = [" hana ", "ABEL", " selam tesfaye "]
# Clean each name, then join themIn the editor, press Escape then Tab to move on.
መፍትሄውን አሳይHide the solution
This is one way to solve it, not the only one. If yours prints the same thing, it works.
typed = [" hana ", "ABEL", " selam tesfaye "]
clean = []
for name in typed:
clean.append(name.strip().title())
print(", ".join(clean))ዋና ዋና ነጥቦች
- A method is a function called with a dot:
name.strip(). - Strings are immutable, so string methods never change the string; they return a new one. Keep it with
name = name.strip(). split()cuts at any run of spaces;split(" ")cuts at every single space.", ".join(words)is called on the separator and takes only strings.findreturns-1when the text is missing;indexraisesValueError.replacereplaces every match.- Ge'ez letters have no case, so
upper()andlower()leave them unchanged.