What are Strings in Python?
A string in Python is a sequence of characters used to represent text. Strings are immutable, meaning once created, their contents cannot be changed.
Examples of Strings:
# Strings with single quotes
string1 = 'Hello, World!'
print(string1)
# Strings with double quotes
string2 = "Python is fun!"
print(string2)
# Strings with triple quotes (multiline string)
string3 = '''This is
a multiline
string.'''
print(string3)
String Indexing and Slicing
Python strings are indexed, which means each character in a string has a specific position. Indexing starts from 0 for the first character and goes up to n-1 for the last character. You can also use negative indexing, where -1 represents the last character.
Example of Indexing:
text = "Python"
print(text[0]) # Output: P (First character)
print(text[-1]) # Output: n (Last character)
String Slicing:
String slicing is used to extract a part of the string by specifying a start and end index.
text = "Programming"
print(text[0:6]) # Output: Progra (Characters from index 0 to 5)
print(text[3:]) # Output: gramming (From index 3 to the end)
print(text[:4]) # Output: Prog (From start to index 3)
print(text[::2]) # Output: Pormig (Every second character)
Common String Operations
Python provides a wide range of operations and methods to manipulate strings.
1. String Concatenation
You can combine strings using the +
operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
2. String Repetition
Use the *
operator to repeat strings.
text = "Python "
print(text * 3) # Output: Python Python Python
3. String Length
The len() function returns the number of characters in a string.
text = "Programming"
print(len(text)) # Output: 11
String Methods
Python has numerous built-in string methods that make string manipulation easy. Here are some of the most commonly used methods:
1. upper() and lower()
Convert a string to uppercase or lowercase.
text = "Hello Python"
print(text.upper()) # Output: HELLO PYTHON
print(text.lower()) # Output: hello python
2. strip()
Remove leading and trailing whitespace.
text = " Python "
print(text.strip()) # Output: Python
3. replace()
Replace a substring with another.
text = "I love Java"
print(text.replace("Java", "Python")) # Output: I love Python
4. split()
Split a string into a list of substrings.
text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'banana', 'cherry']
5. join()
Join elements of a list into a single string.
fruits = ['apple', 'banana', 'cherry']
result = ", ".join(fruits)
print(result) # Output: apple, banana, cherry
6. find()
Find the first occurrence of a substring.
text = "Python programming"
index = text.find("program")
print(index) # Output: 7
7. isnumeric() and isalpha()
Check if a string contains only numbers or only alphabets.
text = "12345"
print(text.isnumeric()) # Output: True
text = "Python"
print(text.isalpha()) # Output: True
Escape Characters
Escape characters allow you to include special characters in strings. They start with a backslash (\).
Examples of Escape Characters:
text = "He said, \"Python is amazing!\""
print(text) # Output: He said, "Python is amazing!"
text = 'It\'s a sunny day.'
print(text) # Output: It's a sunny day.
String Formatting
String formatting provides a way to include variables and expressions in strings.
1. Using f-strings (Recommended):
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.
2. Using format() Method:
name = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Bob and I am 30 years old.
Immutable Nature of Strings
Strings are immutable, meaning you cannot change them after they are created. Any operation that modifies a string creates a new string instead of altering the original.
Example:
text = "Hello"
text[0] = "h" # This will raise an error