String Methods
beginner12 min readLesson 11 of 169
strip, upper, replace, split, join โ the everyday text toolkit.
Methods are functions attached to values โ call them with a dot. The everyday string toolkit:
s = " Hello, Python "
s.strip() # remove surrounding spaces
s.upper() # ' HELLO, PYTHON '
s.lower()
s.replace("l", "L")
s.count("l") # count occurrences
s.find("Py") # index of first match, or -1
"py".upper()
Methods return new strings โ they never change the original (immutability):
name = "minh"
name.upper() # 'MINH' โ but name is still 'minh'!
name = name.upper() # re-assign to keep the result
Splitting and joining
The workhorse pair for text data:
"do-re-mi".split("-") # ['do', 're', 'mi']
"-".join(["a", "b"]) # 'a-b'
"line1,line2".split(",") # ['line1', 'line2']
split() with no argument splits on any whitespace โ perfect for sentences.