Python Strings: A Comprehensive
Guide
1. String Creation
In Python, strings are created by enclosing characters inside single (' ') or double (" ") quotes.
Example:
str1 = 'Hello'
str2 = "World"
print(str1, str2)
Output:
Hello World
2. String Concatenation
You can concatenate two or more strings using the + operator.
Example:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)
Output:
Hello World
3. Repeating Strings
You can repeat a string multiple times using the * operator.
Example:
str1 = "Hi! "
print(str1 * 3)
Output:
Hi! Hi! Hi!
4. String Length
To find the length of a string, use the len() function.
Example:
str1 = "Python"
print(len(str1))
Output:
6
5. Accessing Characters (Indexing)
Strings in Python are indexed, which means each character has a position (starting from 0). You
can access individual characters using square brackets.
Example:
• str1 = "Python"
• first_char = str1[0] # Output: "P"
• last_char = str1[-1] # Output: "n"
6. Slicing
You can extract a portion of a string (substring) by specifying a range of indices. The format is:
string[start:end:step], where 'start' is the index where the slice starts, and 'end' is where it stops
(not inclusive).
Example:
• str1 = "Python"
• substring = str1[0:4] # Output: "Pyth"
7. Strings Are Immutable
Strings in Python are immutable, meaning once created, their content cannot be changed.
Example:
str1 = "Hello"
# This will throw an error
# str1[0] = "h"
8. Traversing Through Strings
a. Using for Loop
You can traverse each character in a string using a for loop.
Example:
str1 = "Python"
for char in str1:
print(char)
Output:
P
y
t
h
o
n
b. Using while Loop
You can also use a while loop to traverse a string by index.
Example:
str1 = "Python"
i=0
while i < len(str1):
print(str1[i])
i += 1
Output:
P
y
t
h
o
n
9. Conditional Statements
a. Using if
You can check conditions in a string using if.
Example:
str1 = "Python"
if "P" in str1:
print("P is present")
Output:
P is present
b. Using if-else
Use if-else to define an alternative action when the condition is False.
Example:
str1 = "Python"
if "A" in str1:
print("A is present")
else:
print("A is not present")
Output:
A is not present
c. Using if-elif-else
You can have multiple conditions using if-elif-else.
Example:
str1 = "Python"
if "A" in str1:
print("A is present")
elif "P" in str1:
print("P is present")
else:
print("None found")
Output:
P is present
10. Python String Methods
A variety of methods are available for string manipulation in Python. Below are some commonly
used methods with examples:
Method Syntax Description Example Output
upper() string.upper() Converts all str1 = "hello" HELLO
characters to print(str1.upper())
uppercase.
lower() string.lower() Converts all str1 = "HELLO" hello
characters to print(str1.lower())
lowercase.
capitalize() string.capitalize() Capitalizes str1 = "hello world" Hello
the first letter print(str1.capitalize()) world
of the string.
title() string.title() Capitalizes str1 = "hello world" Hello
the first letter print(str1.title()) World
of each word.
strip() string.strip() Removes str1 = " hello " hello
leading and print(str1.strip())
trailing
spaces.
replace() string.replace(old, new) Replaces all str1 = "hello world" hello
occurrences print(str1.replace("world", Python
of old with "Python"))
new.
split() string.split() Splits the str1 = "hello world" ['hello',
string into a print(str1.split()) 'world']
list of
substrings.
join() 'separator'.join(iterable) Joins words = ['hello', 'world'] hello
elements of print(' '.join(words)) world
an iterable
(like a list)
into a string.
find() string.find(substring) Returns the str1 = "hello world" 6
lowest index print(str1.find("world"))
of the
substring or -
1 if not
found.
count() string.count(substring) Returns the str1 = "banana" 3
number of print(str1.count("a"))
occurrences
of the
substring.