String Built-in Functions
Python strings have many useful built-in methods (all return a new string/value — strings are immutable).
count() and find()
s = "banana"
print(s.count("a")) # 3
print(s.find("na")) # 2 (index of first occurrence)
print(s.find("xyz")) # -1 (not found)
capitalize(), title(), lower(), upper(), swapcase()
s = "python PROGRAMMING language"
print(s.capitalize()) # 'Python programming language'
print(s.title()) # 'Python Programming Language'
print(s.lower()) # 'python programming language'
print(s.upper()) # 'PYTHON PROGRAMMING LANGUAGE'
print(s.swapcase()) # 'PYTHON programming LANGUAGE'
replace()
s = "I like Java"
print(s.replace("Java", "Python")) # 'I like Python'
join()
Joins elements of an iterable into a single string, using the calling string as separator.
words = ["Python", "is", "fun"]
print(" ".join(words)) # 'Python is fun'
print("-".join(words)) # 'Python-is-fun'
print("".join(["H","i"])) # 'Hi'
isspace(), isdigit()
print(" ".isspace()) # True
print("abc".isspace()) # False
print("12345".isdigit()) # True
print("12a45".isdigit()) # False
split()
Breaks a string into a list, using whitespace (or a given separator) as delimiter.
s = "Python is fun"
print(s.split()) # ['Python', 'is', 'fun']
csv = "Riya,21,BCA"
print(csv.split(",")) # ['Riya', '21', 'BCA']
startswith() and endswith()
s = "hello.py"
print(s.startswith("hello")) # True
print(s.endswith(".py")) # True
print(s.endswith(".txt")) # False
Quick reference table
| Method | Purpose |
|---|---|
count(x) | Number of occurrences of x |
find(x) | Index of first occurrence, or -1 |
capitalize() | First letter uppercase, rest lowercase |
title() | First letter of every word uppercase |
lower() / upper() | Convert case |
swapcase() | Flip upper ⇄ lower |
replace(old,new) | Replace all occurrences |
join(iterable) | Join items with the string as separator |
isspace() | True if all characters are whitespace |
isdigit() | True if all characters are digits |
split(sep) | Split into a list of substrings |
startswith(x) / endswith(x) | Prefix/suffix check |
Combined example — word frequency
sentence = "python is easy python is fun"
words = sentence.split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq) # {'python': 2, 'is': 2, 'easy': 1, 'fun': 1}