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.
s = "Ciao"
s.upper() # 'CIAO' (nuova stringa)
s # 'Ciao' (originale invariata)To "update" assign the result: s = s.upper().
Uppercase, lowercase, case control
"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.
" ciao ".strip() # 'ciao'
" ciao ".lstrip() # 'ciao '
" ciao ".rstrip() # ' ciao'
"___ciao___".strip("_") # 'ciao' (argomento = caratteri da togliere)Split and rejoin: split / join
"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
"ciao mondo".replace("mondo", "Python") # 'ciao Python'
"aaaa".replace("a", "b", 2) # 'bbaa' (max 2 sostituzioni)Content tests
"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") # 2find 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
Given `name = ' Ada Lovelace '`, compute `cleaned` as `name` without edge spaces and all lowercase. Evaluate `cleaned`.
Show hint
Chain the methods: first strip(), then lower().
Solution available after 3 attempts
Review exercise
Given `csv = 'mela,pera,kiwi'`, obtain the list `fruits` by splitting on comma, then rebuild `slash_separated` joining with ' / '. Evaluate `slash_separated`.
Show hint
split breaks apart, join puts back together.
Solution available after 3 attempts
Additional challenge
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.
Show hint
Combine the calls in a chain: raw_text.strip().upper().
Solution available after 3 attempts