Strings in Python: Introduction & Operations
In Python, a string is a sequence of characters. Strings are enclosed in single (') or double
(") quotes. You can perform various operations on strings like concatenation, slicing, and
traversal. Strings in Python are immutable, meaning their content cannot be changed once
created.
1. String Operations
a. Concatenation:
Concatenation is the process of combining two or more strings.
Example:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: "Hello World"
b. Repetition:
Repetition is used to repeat a string a given number of times.
Example:
str = "Python "
result = str * 3
print(result) # Output: "Python Python Python "
c. Membership:
You can check if a substring exists within a string using in or not in.
Example:
str = "Hello, World!"
print("Hello" in str) # Output: True
print("Hi" not in str) # Output: True
d. Slicing:
Slicing extracts a part of a string using the syntax: string[start:end:step].
Example:
str = "Hello, World!"
print(str[0:5]) # Output: "Hello"
print(str[7:]) # Output: "World!"
print(str[:5]) # Output: "Hello"
print(str[-6:]) # Output: "World!"
2. Traversing a String Using Loops
You can loop through the characters of a string using a for loop.
Example:
str = "Hello"
for char in str:
print(char)
Output:
H
e
l
l
o
3. String Built-in Functions and Methods
Python provides several built-in methods for working with strings:
a. len():
Returns the length (number of characters) of a string.
Example:
str = "Hello"
print(len(str)) # Output: 5
b. capitalize():
Capitalizes the first letter of the string.
Example:
str = "hello"
print(str.capitalize()) # Output: "Hello"
c. title():
Capitalizes the first letter of each word in the string.
Example:
str = "hello world"
print(str.title()) # Output: "Hello World"
d. lower():
Converts all characters in the string to lowercase.
Example:
str = "HELLO"
print(str.lower()) # Output: "hello"
e. upper():
Converts all characters in the string to uppercase.
Example:
str = "hello"
print(str.upper()) # Output: "HELLO"
f. count():
Returns the number of occurrences of a substring in the string.
Example:
str = "hello world, hello everyone"
print(str.count("hello")) # Output: 2
g. find():
Returns the index of the first occurrence of a substring. Returns -1 if not found.
Example:
str = "hello world"
print(str.find("world")) # Output: 6
print(str.find("python")) # Output: -1
h. index():
Similar to find(), but raises a ValueError if the substring is not found.
Example:
str = "hello world"
print(str.index("world")) # Output: 6
# print(str.index("python")) # Raises ValueError
i. endswith():
Checks if the string ends with a specified substring. Returns True or False.
Example:
str = "hello world"
print(str.endswith("world")) # Output: True
j. startswith():
Checks if the string starts with a specified substring. Returns True or False.
Example:
str = "hello world"
print(str.startswith("hello")) # Output: True
k. isalnum():
Returns True if all characters in the string are alphanumeric (letters or digits).
Example:
str = "Hello123"
print(str.isalnum()) # Output: True
l. isalpha():
Returns True if all characters in the string are alphabetic.
Example:
str = "Hello"
print(str.isalpha()) # Output: True
m. isdigit():
Returns True if all characters in the string are digits.
Example:
str = "12345"
print(str.isdigit()) # Output: True
n. islower():
Returns True if all characters in the string are lowercase.
Example:
str = "hello"
print(str.islower()) # Output: True
o. isupper():
Returns True if all characters in the string are uppercase.
Example:
str = "HELLO"
print(str.isupper()) # Output: True
p. isspace():
Returns True if the string contains only whitespace characters.
Example:
str = " "
print(str.isspace()) # Output: True
q. lstrip(), rstrip(), strip():
lstrip() removes whitespace from the left side.
rstrip() removes whitespace from the right side.
strip() removes whitespace from both sides.
Example:
str = " Hello World! "
print(str.lstrip()) # Output: "Hello World! "
print(str.rstrip()) # Output: " Hello World!"
print(str.strip()) # Output: "Hello World!"
r. replace():
Replaces a substring with another substring.
Example:
str = "Hello World"
print(str.replace("World", "Python")) # Output: "Hello Python"
s. join():
Joins the elements of an iterable (list, tuple) into a string, with a separator.
Example:
words = ["Hello", "World"]
print(" ".join(words)) # Output: "Hello World"
t. partition():
Splits the string into three parts: the part before the separator, the separator itself, and the part
after the separator.
Example:
str = "Hello World"
print(str.partition(" ")) # Output: ('Hello', ' ', 'World')
u. split():
Splits the string into a list of substrings based on a separator.
Example:
str = "Hello World"
print(str.split()) # Output: ['Hello', 'World']