Python Strings: Basic Operations
Strings in Python are sequences of characters used to store and manipulate text data. Python provides various methods to work with strings.
**Creating Strings**
Strings can be created by enclosing characters in single or double quotes:
string1 = “Hello, World!”
string2 = ‘Python Programming’
**String Operations**
Strings support operations such as concatenation and repetition:
concatenated = string1 + ” ” + string2
repeated = string1 * 2
**String Methods**
Python strings come with a range of methods:
– `upper()`: Converts all characters to uppercase.
– `lower()`: Converts all characters to lowercase.
– `strip()`: Removes leading and trailing whitespace.
– `replace()`: Replaces a specified substring with another.
**Example**:
message = ” Welcome to Python! ”
clean_message = message.strip()
print(clean_message.upper()) # Output: “WELCOME TO PYTHON!”
**String Formatting**
You can format strings using f-strings or the `format()` method:
name = “Alice”
age = 25
print(f”Name: {name}, Age: {age}”)
**Conclusion**
Understanding string operations and methods is essential for manipulating text data effectively in Python.