Strings
What are strings?
In Python, a string is a sequence of characters. Strings can contain letters, numbers, and symbols, and can be used to represent text. They are enclosed in either single or double quotes.
Single and Multiline Strings
A single-line string is a string that is contained on one line. To create a single-line string in Python, you can use either single quotes or double quotes:
my_string = 'This is a single-line string.'
another_string = "This is also a single-line string."
A multiline string, on the other hand, is a string that spans multiple lines. To create a multiline string, you can use triple quotes (either single or double quotes) like this:
multiline_string = '''This is a multiline
string that spans multiple
lines.'''
You can also use the backslash character \
to indicate that a string should continue on the next line:
multiline_string = 'This is a multiline \
string that spans multiple \
lines.'
Use of single or double quotes
In Python, you can use either single or double quotes to create a string. There is no functional difference between the two, but it can be useful to use one or the other depending on the situation. For example, if you want to include a single quote within a string that is enclosed in single quotes, you would need to escape the single quote:
my_string = 'I\'m learning Python.'
Alternatively, you could use double quotes to enclose the string:
my_string = "I'm learning Python."
Escape Characters
Escape characters are special characters that are used to represent certain characters within a string. They are denoted by a backslash character \
. Some common escape characters include:
\n
: newline character\t
: tab character\\
: backslash character\'
: single quote character\"
: double quote character
Here's an example that uses escape characters:
my_string = "This is a string with a\nnew line character."
print(my_string)
Output:
This is a string with a
new line character.
String Formatting
String formatting is a way to include variables or expressions within a string. There are several ways to do string formatting in Python, including using the format()
method, f-strings, and %
-formatting.
format()
method
The format()
method is a built-in method for strings that allows you to insert values into a string. You can do this by using placeholders (curly braces {}
) within the string, and then passing in values as arguments to the format()
method. Here's an example:
name = "John"
age = 30
my_string = "My name is {} and I am {} years old.".format(name, age)
print(my_string)
Output:
My name is John and I am 30 years old.
You can also use numbered placeholders if you want to reuse the same value multiple times:
my_string = "My name is {0} and I am {1} years old. {0} is my name.".format(name, age)
print(my_string)
Output:
My name is John and I am 30 years old. John is my name.
f-strings
f-strings (short for "formatted strings") are a newer way of doing string formatting in Python 3.6 and later. They are similar to the format()
method, but use a prefix of f
before the string and allow you to directly embed expressions and variables within the string by enclosing them in curly braces {}
. Here's an example:
name = "John"
age = 30
my_string = f"My name is {name} and I am {age} years old."
print(my_string)
Output:
My name is John and I am 30 years old.
You can also do arithmetic and other operations within the curly braces:
my_string = f"My name is {name} and in 5 years I will be {age+5} years old."
print(my_string)
Output:
My name is John and in 5 years I will be 35 years old.
%
-formatting
The %
-formatting method is an older way of doing string formatting in Python. It works by using the %
operator and a tuple of values to replace placeholders within a string. Here's an example:
name = "John"
age = 30
my_string = "My name is %s and I am %d years old." % (name, age)
print(my_string)
Output:
My name is John and I am 30 years old.
Common String-Specific Operations
Python provides many built-in string-specific operations that allow you to manipulate strings in various ways. It's important to note that strings in Python are immutable, meaning that they cannot be modified directly. Instead, string methods return new strings with the desired changes.
Here are some of the most commonly used string methods. These are just a few examples of the many built-in string methods in Python. For a full list of available string methods, check out the official Python documentation.
Upper/lower
The upper()
and lower()
methods allow you to convert a string to all uppercase or all lowercase, respectively. Both methods return a new string with the changes applied.
my_string = "Hello, World!"
print(my_string.upper()) # returns a new string: "HELLO, WORLD!"
print(my_string.lower()) # returns a new string: "hello, world!"
Strip
The strip()
method removes any whitespace characters (spaces, tabs, newlines) from the beginning and end of a string and returns a new string.
my_string = " Hello, World! "
print(my_string.strip()) # returns a new string: "Hello, World!"
You can also use lstrip()
and rstrip()
to strip only from the left or right side of the string, respectively.
Replace
The replace()
method replaces all occurrences of a substring within a string with another substring and returns a new string.
my_string = "Hello, World!"
print(my_string.replace("World", "Python")) # returns a new string: "Hello, Python!"
Split
The split()
method splits a string into a list of substrings, using a specified delimiter character. If no delimiter is specified, it defaults to splitting on whitespace characters. It returns a list of strings.
my_string = "Hello, World!"
print(my_string.split(",")) # returns a list of strings: ["Hello", " World!"]
Strings are Arrays of Characters
In Python, strings are actually arrays of individual characters. This means that you can use array-style indexing and slicing to access and manipulate specific parts of a string.
It's important to note that Python uses zero-indexing, which means that the first character in a string has an index of 0, the second character has an index of 1, and so on. Negative indices count from the end of the string, with -1 representing the last character, -2 representing the second-to-last character, and so on.
len
function
The len()
function returns the length of a string, which is the number of characters in the string.
my_string = "Hello, World!"
print(len(my_string)) # prints 13
in
and not in
keywords
The in
and not in
keywords allow you to check whether a substring is present within a string.
my_string = "Hello, World!"
print("World" in my_string) # prints True
print("Python" not in my_string) # prints True
Slicing
Slicing allows you to extract a portion of a string by specifying a start
and end
index. The syntax for slicing is string[start:end]
, where start
is the index of the first character to include, and end
is the index of the first character to exclude.
my_string = "Hello, World!"
print(my_string[0:5]) # prints "Hello"
print(my_string[7:]) # prints "World!"
You can also use negative indices to count from the end of the string:
my_string = "Hello, World!"
print(my_string[-6:-1]) # prints "World"
String Concatenation
String concatenation is the process of combining two or more strings into a single string. In Python, you can use the +
operator to concatenate strings:
str1 = "Hello"
str2 = "World"
my_string = str1 + " " + str2
print(my_string) # prints "Hello World"
Alternatively, you can use the join()
method to concatenate a list of strings:
my_list = ["Hello", "World"]
my_string = " ".join(my_list)
print(my_string) # prints "Hello World"
And that's it! With this tutorial, you should now have a good understanding of strings in Python and how to use them in your programs.