









Python Strings
Basics and Examples
What is a String in Python?
A string in Python is a sequence of characters enclosed in single ('
), double ("
), or triple quotes ('''
or """
).
'Hello, World!'
"Hello, World!"
Strings are used to store text-based information such as names, messages, or any human-readable data.
Creating Strings
You can create a string using single or double quotes interchangeably:
name = 'Arjun'
message = "Hello, World!"
If your string contains quotes inside, use the other type to avoid syntax errors:
quote = "It's a beautiful day"
alt_quote = 'He said, "Hi!"'
Multiline Strings
Use triple quotes when you want to write strings across multiple lines.
poem = """Roses are red,
Violets are blue,
Python is great,
And so are you."""
Accessing Characters in a String
In Python, you can access individual characters in a string using indexing. Each character in the string has a position, called an index, which starts from 0
for the first character and increases by one for each subsequent character.
Here's how you can use positive indexing to access characters from the beginning:
greeting = "Hello"
print(greeting[0]) # H (first character)
print(greeting[4]) # o (fifth character)
Python also supports negative indexing, which allows you to access characters from the end of the string. The last character has an index of -1
, the second last is -2
, and so on.
greeting = "Hello"
print(greeting[-1]) # o (last character)
print(greeting[-2]) # l (second last character)
This flexibility makes it easy to access both ends of a string without needing to know its exact length.
String Slicing
Slicing helps extract parts of a string using the syntax string[start:end]
.
text = "Python"
print(text[0:2]) # Py
print(text[2:]) # thon
print(text[:3]) # Pyt
print(text[-3:]) # hon
Immutability of Strings
Strings in Python are immutable. This means once created, they cannot be changed in place.
word = "Python"
word[0] = "J" # This will raise a TypeError
Common String Methods
Python provides several built-in methods to work with strings:
lower()
: Converts all characters to lowercaseupper()
: Converts all characters to uppercasestrip()
: Removes leading and trailing whitespacereplace(old, new)
: Replaces substringsplit()
: Splits the string into a listjoin()
: Joins elements of a list with a string separator
s = " Learn Python "
print(s.strip()) # 'Learn Python'
print(s.lower()) # ' learn python '
print(s.replace("Python", "Java")) # ' Learn Java '
For complete set of string methods in Python, you may refer String methods.
String Formatting
In Python, you can insert variables directly into strings using f-strings (formatted string literals). This makes it easy to construct readable and dynamic messages.
name = "Arjun"
age = 25
print(f"My name is {name} and I am {age} years old.")
My name is Arjun and I am 25 years old.
Checking Substrings
Python allows you to check whether a certain substring exists within a string using the in
and not in
keywords. These return a boolean value — True
or False
.
msg = "Welcome to Python"
print("Python" in msg) # True, because "Python" is in the string
print("Java" not in msg) # True, because "Java" is not in the string
Looping Through a String
Since strings are sequences of characters, you can loop through them using a for
loop. Each iteration gives you one character from the string.
for char in "Hi":
print(char)
Length of a String
You can find out how many characters are in a string using the built-in len() function. This includes letters, digits, spaces, and symbols.
text = "Python"
print(len(text)) # 6
Validation & Checks
Before working with strings, you might want to validate them:
isalpha()
– checks if all characters are alphabetsisdigit()
– checks if all characters are digitsisalnum()
– checks if all characters are alphanumericisspace()
– checks for only whitespace
val = "123abc"
print(val.isalnum()) # True
print(val.isdigit()) # False