Python Strings
Python strings are sequences of characters, enclosed in either single quotes (”) or double quotes (“”). They are immutable, which means they cannot be modified once created. You can perform various operations on strings in Python, such as concatenation, slicing, formatting, and more.
Here are some examples of working with strings in Python:
- String creation:python
my_string = "Hello, World!"
Accessing characters:
python
print(my_string[0]) # Output: 'H'
print(my_string[-1]) # Output: '!'
String concatenation:
python
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # Output: "Hello, Alice!"
String slicing:
python
print(my_string[7:12]) # Output: "World"
print(my_string[:5]) # Output: "Hello"
print(my_string[7:]) # Output: "World!"
String length:
python
print(len(my_string)) # Output: 13
String methods:
python
print(my_string.upper()) # Output: "HELLO, WORLD!"
print(my_string.lower()) # Output: "hello, world!"
print(my_string.replace("Hello", "Hi")) # Output: "Hi, World!"
print(my_string.split(",")) # Output: ['Hello', ' World!']
String formatting:
python
name = "Bob" age = 25 formatted_string = "My name is {} and I'm {} years old.".format(name, age) print(formatted_string) # Output: "My name is Bob and I'm 25 years old." # Using f-strings (Python 3.6+) formatted_string = f"My name is {name} and I'm {age} years old." print(formatted_string) # Output: "My name is Bob and I'm 25 years old."
These are just a few examples of what you can do with strings in Python. Strings in Python have many more methods and functionalities, so feel free to explore the Python documentation for more information.