Python strings are a versatile data type that allow you to store textual information. Python strings are immutable, which means once created, their value cannot be altered. In this tutorial, we will look at how you can perform various operations on strings, such as creation, slicing, and manipulation.
Table of Contents
1. Creating Python Strings
You can create a string by enclosing text within single quotes (' '
) or double quotes (" "
).
# Using single quotes
str1 = 'Hello, World!'
print(str1)
# Using double quotes
str2 = "Hello, World!"
print(str2)
Output:
Hello, World!
Hello, World!
2. Accessing Python Strings Elements
Strings are indexed, and you can access individual characters using square brackets []
.
str3 = "Python"
print(str3[0]) # Output: P
print(str3[-1]) # Output: n
3. String Concatenation
You can concatenate two or more strings using the +
operator.
str4 = "Hello" + " " + "World!"
print(str4) # Output: Hello World!
4. String Length
To find the length of a string, you can use the len()
function.
str5 = "Python"
length = len(str5)
print(length) # Output: 6
5. String Methods
Python provides various methods to manipulate and work with strings.
5.1 upper()
and lower()
str6 = "Python"
print(str6.upper()) # Output: PYTHON
print(str6.lower()) # Output: python
5.2 strip()
str7 = " Python "
print(str7.strip()) # Output: Python
5.3 replace()
str8 = "Python is fun!"
print(str8.replace("fun", "awesome")) # Output: Python is awesome!
6. String Formatting
You can use various techniques to format strings in Python. More examples on string formatting
6.1 Using f-strings
name = "Alice"
print(f"Hello, {name}!") # Output: Hello, Alice!
6.2 Using .format()
name = "Bob"
print("Hello, {}!".format(name)) # Output: Hello, Bob!
This is just the tip of the iceberg when it comes to Python’s string capabilities. By mastering these basics, you’ll be well on your way to becoming proficient at string manipulation in Python.