Strings in Python
Python offers a rich set of built-in functions and methods for manipulating strings. These
functions do not modify the original string but return a new string with the desired changes.
Common String Functions and Methods:
Case Conversion:
upper(): Converts all characters to uppercase.
lower(): Converts all characters to lowercase.
capitalize(): Converts the first character to uppercase and the rest to lowercase.
title(): Converts the first character of each word to uppercase.
swapcase(): Swaps the case of all characters (uppercase to lowercase, and vice-
versa).
Whitespace and Character Removal:
strip(): Removes leading and trailing whitespace.
lstrip(): Removes leading whitespace.
rstrip(): Removes trailing whitespace.
Searching and Replacing:
find(substring): Returns the lowest index of the substring if found, otherwise -1.
rfind(substring): Returns the highest index of the substring if found, otherwise -1.
index(substring): Similar to find(), but raises a ValueError if the substring is not
found.
rindex(substring): Similar to rfind(), but raises a ValueError if the substring is not
found.
replace(old, new): Replaces all occurrences of old with new.
Splitting and Joining:
split(separator): Splits the string into a list of substrings based on the separator.
join(iterable): Joins elements of an iterable (e.g., a list of strings) into a single
string, using the string itself as a separator.
Checking String Properties:
isalnum(): Returns True if all characters are alphanumeric.
isalpha(): Returns True if all characters are alphabetic.
isdigit(): Returns True if all characters are digits.
islower(): Returns True if all cased characters are lowercase.
isupper(): Returns True if all cased characters are uppercase.
isspace(): Returns True if all characters are whitespace.
startswith(prefix): Returns True if the string starts with the specified prefix.
endswith(suffix): Returns True if the string ends with the specified suffix.
Other Useful Functions:
len(string): Returns the length of the string.
count(substring): Returns the number of occurrences of the substring.
format(): Formats strings using placeholders and arguments.
Example Usage:
Python
my_string = " Hello, World! "
# Case conversion
print(my_string.upper()) # Output: HELLO, WORLD!
print(my_string.lower()) # Output: hello, world!
print(my_string.capitalize()) # Output: hello, world!
# Whitespace removal
cleaned_string = my_string.strip()
print(cleaned_string) # Output: Hello, World!
# Searching and replacing
print(cleaned_string.find("World")) # Output: 7
print(cleaned_string.replace("World", "Python")) # Output: Hello, Python!
# Splitting and joining
words = cleaned_string.split(", ")
print(words) # Output: ['Hello', 'World!']
new_string = "-".join(words)
print(new_string) # Output: Hello-World!
# Checking properties
print("Python".isalpha()) # Output: True
print("123".isdigit()) # Output: True
String Functions
1. upper()
Converts all characters to uppercase.
s = "hello"
print([Link]()) # Output: HELLO ---
2. lower()
Converts all characters to lowercase.
s = "HeLLo"
print([Link]()) # Output: hello ---
3. capitalize()
Converts first character to uppercase, rest to lowercase.
s = "hello world"
print([Link]()) # Output: Hello world ---
�
4. title()
Capitalizes first letter of each word.
s = "hello world"
print([Link]()) # Output: Hello World ---
5. strip()
Removes leading and trailing whitespace.
s = " hello "
print([Link]()) # Output: 'hello' ---
6. lstrip() / rstrip()
Removes leading / trailing whitespace.
print(" hi".lstrip()) # Output: 'hi'
print("hi ".rstrip()) # Output: 'hi' ---
7. replace(old, new)
Replaces substring.
s = "banana"
print([Link]("a", "@")) # Output: b@n@n@ ---
�
8. split(delimiter)
Splits string into list.
s = "a,b,c"
print([Link](",")) # Output: ['a', 'b', 'c'] ---
9. join(iterable)
Joins iterable elements using string as separator.
words = ["a", "b", "c"]
print("-".join(words)) # Output: a-b-c
---
10. find(sub)
Returns lowest index of sub. Returns -1 if not found.
s = "banana"
print([Link]("a")) # Output: 1 ---
11. rfind(sub)
Returns highest index of sub.
print("banana".rfind("a")) # Output: 5 ---
12. index(sub)
Like find(), but raises error if not found.
print("banana".index("n")) # Output: 2
# print("banana".index("x")) # Error! ---
13. count(sub)
Counts occurrences of sub.
print("banana".count("a")) # Output: 3 ---
14. startswith(prefix)
Checks if string starts with a value.
print("hello".startswith("he")) # Output: True ---
15. endswith(suffix)
Checks if string ends with a value.
print("hello".endswith("lo")) # Output: True ---
16. isalpha()
True if all characters are letters.
print("abc".isalpha()) # Output: True ---
17. isdigit()
True if all characters are digits.
print("123".isdigit()) # Output: True ---
18. isalnum()
True if all characters are letters or digits.
print("abc123".isalnum()) # Output: True ---
19. islower() / isupper()
Check if string is all lowercase / uppercase.
print("abc".islower()) # Output: True
print("ABC".isupper()) # Output: True ---
20. zfill(width)
Pads string on the left with zeros.
print("42".zfill(5)) # Output: 00042