Skip to main content
eLearner.app
Module 4 · Lesson 1 of 413/36 in the course~12 min
Module lessons (1/4)

String methods

Strings in Python are immutable: every method that "modifies" them actually returns a new string, the original stays as it is.

Python
s = "Ciao"
s.upper()   # 'CIAO'   (nuova stringa)
s           # 'Ciao'   (originale invariata)

To "update" assign the result: s = s.upper().

Uppercase, lowercase, case control

Python
"Ciao".upper()        # 'CIAO'
"CIAO".lower()        # 'ciao'
"ciao mondo".title()  # 'Ciao Mondo'
"ciao".capitalize()   # 'Ciao'
"CiAo".swapcase()     # 'cIaO'

Cleanup: strip

Removes whitespace (spaces, tabs, newlines) from the edges.

Python
"  ciao  ".strip()       # 'ciao'
"  ciao  ".lstrip()      # 'ciao  '
"  ciao  ".rstrip()      # '  ciao'
"___ciao___".strip("_")  # 'ciao'   (argomento = caratteri da togliere)

Split and rejoin: split / join

Python
"a,b,c".split(",")          # ['a', 'b', 'c']
"  ciao  mondo".split()     # ['ciao', 'mondo']   (split su whitespace, salta i vuoti)
",".join(["a", "b", "c"])  # 'a,b,c'

Fundamental idiom: "separator".join(list_of_strings). All elements must be strings, otherwise TypeError.

Replacement: replace

Python
"ciao mondo".replace("mondo", "Python")   # 'ciao Python'
"aaaa".replace("a", "b", 2)               # 'bbaa'   (max 2 sostituzioni)

Content tests

Python
"image.png".endswith(".png")   # True
"http://".startswith("http")    # True
"ciao" in "ciao mondo"          # True   (operatore in)
"ciao mondo".find("mondo")      # 5      (-1 se non trovato)
"ciao mondo".count("o")         # 2

find returns -1 if the substring is not present; index instead raises ValueError.

Strings are immutable

In Python, strings are immutable: no string method modifies the original string; instead, they always return a new string. If you write s.upper(), the variable s remains unchanged. To save the modification, you must reassign it: s = s.upper().

Try it

Exercise#python.m4.l1.e1
Attempts: 0Loading…

Given `name = ' Ada Lovelace '`, compute `cleaned` as `name` without edge spaces and all lowercase. Evaluate `cleaned`.

Loading editor…
Show hint

Chain the methods: first strip(), then lower().

Solution available after 3 attempts

Review exercise

Exercise#python.m4.l1.e2
Attempts: 0Loading…

Given `csv = 'mela,pera,kiwi'`, obtain the list `fruits` by splitting on comma, then rebuild `slash_separated` joining with ' / '. Evaluate `slash_separated`.

Loading editor…
Show hint

split breaks apart, join puts back together.

Solution available after 3 attempts

Additional challenge

Exercise#python.m4.l1.e3
Attempts: 0Loading…

Given the string `raw_text = " hello world "`, remove the leading and trailing whitespaces with `.strip()` and convert the text to uppercase. Store the cleaned result in `clean_text` and evaluate it.

Loading editor…
Show hint

Combine the calls in a chain: raw_text.strip().upper().

Solution available after 3 attempts