String methods
String methods
String Methods
Python strings come with a rich set of built-in methods. Since strings are immutable, every method returns a new string — the original is never modified.
Case Methods
Useful in CP when problems say "case-insensitive comparison" — just lowercase both strings before comparing:
Checking String Content
These methods return True or False:
Checking character type inside a loop:
Searching
find(sub) and rfind(sub)
Returns the index of the first occurrence of sub, or -1 if not found:
You can also specify a search range find(sub, start, end):
count(sub)
Counts non-overlapping occurrences:
startswith(prefix) and endswith(suffix)
Frequently used in CP to check format or conditions on strings.
Modifying (Returns New String)
replace(old, new)
Replaces all occurrences of old with new:
Replace only the first N occurrences with the third argument:
strip(), lstrip(), rstrip()
Removes whitespace (or specified characters) from the edges:
You can also pass specific characters to strip:
Very useful when reading input that might have trailing spaces or newlines.
Splitting and Joining
These two methods are the most important ones for competitive programming.
split(sep)
Splits a string into a list of substrings:
With no argument, split() splits on any whitespace and ignores leading/trailing spaces. With an argument, it splits on that specific separator:
You have been using split() since Module 3 for reading input — now you know exactly what it does.
join(iterable)
The opposite of split() — joins a list of strings into one, placing the calling string between each element:
This is the efficient way to build a string from many pieces. Instead of doing result += char in a loop (which creates a new string each time), collect into a list and join once at the end:
A very common CP pattern — filter or transform characters and join: