9.8 String Functions
Built-in functions that operate on strings from the outside -- len(), max(), min(), sorted(), chr(), ord(), ascii(), repr(), and str() -- as distinct from methods called on the string itself.
These are global built-in functions that accept a string as an argument, rather than methods called on the string object itself (len(s) vs. s.upper()).
| Function | Example | Result |
|---|---|---|
len() | len("hello") | 5 |
max() | max("hello") | 'o' |
min() | min("hello") | 'e' |
sorted() | sorted("dcba") | ['a','b','c','d'] |
chr() | chr(97) | 'a' |
ord() | ord('a') | 97 |
ascii() | ascii("héllo") | "'h\\xe9llo'" |
repr() | repr("hi\n") | "'hi\\n'" |
str() | str(123) | '123' |
chr() and ord() are inverses — chr() converts a Unicode code point (an integer) to its character, ord() does the reverse. max()/min() on a string compare characters by their code point, the same ordering used in 9.5 String Operators.
>>> ord("A"), chr(65)
(65, 'A')
repr() produces an unambiguous, developer-facing representation — useful in debugging output because it shows exactly what’s in the string, including otherwise-invisible characters like \n:
>>> print("hi\n") # str() / print() interprets the escape
hi
>>> print(repr("hi\n")) # repr() shows it literally
'hi\n'
Quick Interview Answer
“These are functions, not methods — they’re called as
len(s)rather thans.len().len()andsorted()/max()/min()treat a string as an iterable of characters.chr()andord()convert between a character and its Unicode code point, in either direction.str()converts any object to its readable string form, whilerepr()produces an unambiguous, code-like representation — the distinction matters most in debugging, whererepr()reveals hidden characters like\nthatstr()/print()would render literally.”
Common Mistakes
- Calling
s.len()instead oflen(s)— length is a built-in function, not a string method, unlike most other string operations. - Confusing
str()andrepr()output for debugging —print(value)usesstr()and can hide escape sequences or ambiguity thatrepr(value)would reveal. - Assuming
max("hello")returns the longest substring — on a string it compares individual characters by code point, returning'o', not a substring.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form