Strings are a fundamental data type in Python and can be manipulated in various ways. Strings are enclosed within either single ('), double ("), or triple (''' or “””) quotes. Triple quotes allow for multi-line strings.
Assigning and Printing Strings
We can assign a string to a variable and print it using the print function.
# Assigning a string
greeting = 'Hello, World!'
# Printing a string
print(greeting)
Output:
Hello, World!
String Concatenation
Strings can be concatenated using the + operator:
print("Hello" + " World")
Output:
Hello World
String Slicing
Python allows slicing strings using indices. The slice notation follows the format string[start:end], where start is inclusive, and end is exclusive.
string1 = 'hello world'
print(string1[0:1]) # 'h'
print(string1[0:4]) # 'hell'
print(string1[2:4]) # 'll'
print(string1[:4]) # 'hell'
print(string1[3:]) # 'lo world'
Attempting to modify a string using slicing will result in an error because strings in Python are immutable:
string1[:0] = 'Hai' # TypeError: 'str' object does not support item assignment
However, we can create a new string using concatenation:
print('Hai' + string1[:]) # 'Haihello world'
Using Negative Indices
Negative indices allow accessing elements from the end of the string.
print(string1[-1]) # 'd'
print(string1[-4:-1]) # 'orl'
print(string1[-4:-2]) # 'or'
If the slicing range is incorrect, it may return an empty string:
print(string1[-4:0]) # ''
print(string1[-1:-4]) # ''
print(string1[-11:-1]) # 'hello worl'
Additional String Methods
Python provides several useful methods for string manipulation:
s = " Python Programming "
print(s.lower()) # ' python programming '
print(s.upper()) # ' PYTHON PROGRAMMING '
print(s.strip()) # 'Python Programming' (removes leading/trailing spaces)
print(s.replace("Python", "Ruby")) # ' Ruby Programming '
print(s.split()) # ['Python', 'Programming'] (splits by whitespace)
String Formatting
Python supports f-strings (introduced in Python 3.6) for formatting strings:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 30 years old.
Conclusion
Python provides powerful ways to manipulate strings using slicing, concatenation, and various built-in methods. Understanding these techniques helps in efficient string handling in real-world applications.