Guide Python Beginner

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.

2 min read

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()).

FunctionExampleResult
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 than s.len(). len() and sorted()/max()/min() treat a string as an iterable of characters. chr() and ord() convert between a character and its Unicode code point, in either direction. str() converts any object to its readable string form, while repr() produces an unambiguous, code-like representation — the distinction matters most in debugging, where repr() reveals hidden characters like \n that str()/print() would render literally.”

Common Mistakes

  • Calling s.len() instead of len(s) — length is a built-in function, not a string method, unlike most other string operations.
  • Confusing str() and repr() output for debugging — print(value) uses str() and can hide escape sequences or ambiguity that repr(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