Strings in Python
Hey there! In this guide, we'll explore strings in Python. Strings are sequences of characters that allow you to store and manipulate text efficiently. Let's dive in!
Python Strings​
- Immutable: Strings are immutable, meaning that once created, their contents cannot be changed.
- Indexed: Strings are ordered collections of characters, and you can access individual characters using their index.
- Supports concatenation: You can concatenate strings using the
+
operator. - Supports various methods: Python provides many built-in methods to manipulate strings.
1. Creating a String​
You can create a string using single quotes '
, double quotes "
, or triple quotes '''
or """
for multi-line strings.
my_string = 'Hello, World!' # Create a string using single quotes
another_string = "Python is awesome!" # Create a string using double quotes
multi_line_string = '''This is a
multi-line string.''' # Create a string using triple quotes
print(my_string) # Output: Hello, World!
print(another_string) # Output: Python is awesome!
print(multi_line_string) # Output: This is a
# multi-line string.
2. Accessing Characters​
You can access characters in a string using their index. Python uses zero-based indexing.
my_string = "Hello, World!"
print(my_string[0]) # Access the first character, Output: H
print(my_string[7]) # Access the eighth character, Output: W
3. String Methods​
Python provides various built-in methods to manipulate strings.
my_string = "Python"
length = len(my_string) # Get the length of the string
print(length) # Output: 6
upper_string = my_string.upper() # Convert to uppercase
print(upper_string) # Output: PYTHON
lower_string = my_string.lower() # Convert to lowercase
print(lower_string) # Output: python
replaced_string = my_string.replace("P", "J") # Replace a substring
print(replaced_string) # Output: Jython
4. String Concatenation​
You can concatenate strings using the +
operator.
string1 = "Hello"
string2 = "World"
combined_string = string1 + ", " + string2 + "!" # Concatenate strings
print(combined_string) # Output: Hello, World!
5. String Slicing​
You can slice a string to get a substring.
my_string = "Hello, World!"
substring = my_string[0:5] # Get a substring
print(substring) # Output: Hello
substring2 = my_string[7:] # Get substring from index 7 to end
print(substring2) # Output: World!