Working with Strings in Python
Working with Strings in Python
In Python, strings are sequences of characters enclosed in quotes. They can be single quotes,
double quotes, or even triple quotes for multiline strings. But why do we need strings? Well, as
the great philosopher, Alan Turing, once said, "The only way to do great work is to love what you
do." And what's not to love about working with text?
String Literals
Let's start with the basics. A string literal is a sequence of characters surrounded by quotes. For
example:
my_string = "Hello, World!"
print(my_string) # Output: Hello, World!
But what if we want to include quotes within our string? That's where escaping comes in. We
can use the backslash (\) to escape special characters, like quotes
my_string = "Hello, \"World!\""
print(my_string) # Output: Hello, "World!"
String Operations
Now that we have our string literals, let's perform some operations on them. We can
concatenate strings using the + operator.
greeting = "Hello, "
name = "John"
full_greeting = greeting + name
print(full_greeting) # Output: Hello, John
We can also repeat strings using the + operator.
String Operations
Now that we have our string literals, let's perform some operations on them. We can
concatenate strings using the + operator.
greeting = "Hello, "
name = "John"
full_greeting = greeting + name
print(full_greeting) # Output: Hello, John
We can also repeat strings using the * operator.
repeated_string = "Hello, " * 3
print(repeated_string) # Output: Hello, Hello, Hello,
String Indexing and Slicing
In Python, strings are sequences, which means we can access individual characters using
indexing. Let's take a look:
my_string = "Hello, World!"
print(my_string[0]) # Output: H
print(my_string[-1]) # Output:!
We can also use slicing to extract substrings.
my_string = "Hello, World!"
print(my_string[0:5]) # Output: Hello
print(my_string[7:]) # Output: World!
String Methods
Python provides a variety of methods for working with strings. Let's take a look at a few
examples:
my_string = "Hello, World!"
print(my_string.upper()) # Output: HELLO, WORLD!
print(my_string.lower()) # Output: hello, world!
print(my_string.replace("World", "Universe")) # Output: Hello, Universe!
String Formatting
String formatting is a powerful feature in Python that allows us to insert values into strings. Let's
take a look:
name = "John"
age = 30
print("My name is %s and I am %d years old." % (name, age)) # Output: My name is John and I
am 30 years old.
We can also use f-strings, which provide a more readable and efficient way of formatting strings.
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.") # Output: My name is John and I am 30
years old.
And that's a wrap! With these basics under our belt, we're ready to tackle more advanced string
manipulation techniques in Python.