String
String
ipynb - Colab
keyboard_arrow_down Strings
In Python, a string is a sequence of characters enclosed in either single quotes ( '' ) or double
quotes ( "" ). Strings are one of the fundamental data types in Python and are widely used for
representing textual data. They allow us to store and manipulate text, such as names, sentences,
or even entire documents.
Strings can contain any combination of letters, numbers, symbols, and whitespace characters.
For example, "Hello, World!" and 'I love Python' are both valid string literals in Python.
Motivation
Welcome to your journey of learning about strings in programming! Let's explore the key reasons
why learning about strings is valuable:
Text Manipulation: Strings are essential for working with text data in programming. They
allow us to store and change groups of letters, words, and sentences. With strings, we can
do cool things like getting input from users, processing text, and making text look nice and
organized.
Data Representation and Communication: Strings help us represent and communicate text
information in programs. They are like messengers that help us send and receive text. We
can display messages to users, read and write text from files, and even send text over the
internet. Strings are the language that computers understand when it comes to text.
Problem Solving and Data Analysis: Understanding strings is important for problem-
solving and data analysis. Many real-world problems involve working with text, like finding
specific words, changing parts of a text, or doing calculations based on text. When we
know how to work with strings, we can solve all sorts of interesting problems and analyze
data in new and exciting ways.
Hello, Python!
In this example, we create a string variable named message and assign it the value "Hello,
Python!" . The print() function is then used to display the value of the message variable, which
will output "Hello, Python!" .
John Doe
It's important to note that the choice between single quotes and double quotes is
a matter of personal preference or specific requirements. However, it's
recommended to be consistent in your usage throughout your codebase.
empty_string = ""
print(empty_string)
In this case, the empty_string variable is assigned an empty string value, represented by two
quotation marks with nothing in between. The print() function will output an empty line.
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
John Doe
In this example, we have two string variables first_name and last_name . By using the +
operator and an additional string containing a space, we concatenate the two variables together,
resulting in the full_name variable containing "John Doe" . The print() function displays the
value of full_name .
You can also concatenate string literals directly without using variables:
Hello, World!
In this case, we concatenate the string literals "Hello" , ", " , and "World!" together, resulting
in the greeting variable containing "Hello, World!" .
It's worth noting that when concatenating strings, you can include additional characters or
whitespace between the string variables or literals to format the resulting string as desired.
In Python, string indexing starts at 0, so the first character of a string has an index
of 0, the second character has an index of 1, and so on.
You can use square brackets ( [] ) and the index number to access a specific character in a
string. Here's an example of string indexing:
H
W
In this example, we define a string variable message with the value "Hello, World!" . By using
the square brackets and the index numbers, we access the first character of the string (index 0),
which is "H" , and the eighth character of the string (index 7), which is "W" .
In addition to indexing individual characters, you can also extract a portion of a string using
string slicing.
String slicing allows you to create a new string that includes a specified range of
characters from the original string.
To slice a string, you need to provide the starting index and the ending index (exclusive)
separated by a colon ( : ) inside the square brackets. The starting index is inclusive, meaning
that the character at that index will be included in the slice. The ending index is exclusive,
meaning that the character at that index will not be included in the slice.
Hello
World
In this example, we use string slicing to extract the substring "Hello" from the message string.
The slice message[0:5] starts at index 0 and ends at index 5 (exclusive), including characters
at indices 0, 1, 2.
Here are some additional examples of slicing that use different slicing syntax and step values:
Hello
In this example, we use text[:5] to slice the string text from the beginning up to index 5
(exclusive). This includes characters at indices 0, 1, 2, 3, and 4, resulting in the substring
"Hello" .
World!
Here, we use text[7:] to slice the string text from index 7 to the end. This includes all
characters starting from index 7 to the end of the string, resulting in the substring "World!" .
llo,
In this example, we use text[2:7] to slice the string text from index 2 to index 7 (exclusive).
This includes characters at indices 2, 3, 4, 5, and 6, resulting in the substring "llo, " .
Hlo ol!
Here, we use text[::2] to slice the string text with a step value of 2 . This retrieves every
second character in the string, resulting in the substring "Hlo ol!" .
el,Wr
In this example, we use text[1:10:2] to slice the string text . The start index is 1 , the end
index is 10 (exclusive), and the step value is 2 .
The slicing operation starts at index 1 ( "e" ), includes every second character, and stops at
index 10 ( "d" ). The resulting substring is "el,Wr" .
By specifying both start and end indices along with a step value, you can create customized
slices that skip or include specific characters based on your requirements.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/4. Strings/Notebook.ipynb Cell 21 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/4.%20Strings/Notebook.ipy
line=0'>1</a> text = "Hello, World!"
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/4.%20Strings/Notebook.ipy
line=1'>2</a> print(text[20])
In this example, the string text has a length of 13. However, when we try to access the
character at index 20 , which is beyond the range of valid indices for the string, we encounter an
IndexError . Python raises this error to indicate that the index is out of range.
To avoid this error, ensure that the index used for indexing or slicing is within the valid range of
the string's indices (0 to length-1).
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/4. Strings/Notebook.ipynb Cell 24 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/4.%20Strings/Notebook.ipy
line=0'>1</a> text = "Hello, World!"
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/4.%20Strings/Notebook.ipy
line=1'>2</a> print(text[2.5])
In this example, we try to access the character at index 2.5 of the string text . However, string
indices must be integers, and using a floating-point index raises a TypeError . Python expects
whole numbers for indexing or slicing operations.
To resolve this error, make sure to use integer values for indices when accessing characters or
performing slicing operations on strings.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/4. Strings/Notebook.ipynb Cell 27 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/4.%20Strings/Notebook.ipy
line=0'>1</a> text = "Hello, World!"
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/4.%20Strings/Notebook.ipy
line=1'>2</a> print(text[::0])
In this example, we attempt to slice the string text using a step value of 0 . However, the step
value in a slice operation cannot be zero because it determines the increment or decrement
between successive elements. A step of zero does not provide meaningful iteration and raises a
ValueError .
To resolve this error, use a non-zero step value that suits your intended slicing operation.
HELLO, WORLD!
hello, world!
capitalize() : Capitalizes the first character of a string and converts the remaining
characters to lowercase
Hello, world!
Hello, World!
Hello, World!
Hello, Python!
Using the % operator: This approach is known as "old-style" string formatting and involves
using placeholders ( %s , %d , %f , etc.) to specify where values should be inserted within a
string
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.
The % operator is used to perform string formatting. It allows us to replace the placeholders with
the actual values from the variables. In the example, %s is replaced by the value of the name
variable, and %d is replaced by the value of the age variable.
The values to be inserted into the placeholders are provided in a tuple (name, age) following the
% operator. Don't worry about knowing what tuples are we will cover them in details in a latter
lesson.
Using the format() method: This approach involves using curly braces {} as placeholders
and calling the format() method on the string to specify the values to be inserted
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is John and I am 30 years old.
The print() function is used to display a formatted string, which consists of a template string
with placeholders. The placeholders are represented by curly braces {} .
To insert the actual values into the placeholders, we use the format() method on the string.
This method takes the values to be inserted as arguments in the same order as the placeholders
in the string. In our example, the format() method is called on the template string "My name is
{} and I am {} years old." . We pass the name variable as the first argument and the age
variable as the second argument to the format() method. The format() method replaces the
curly braces {} with the corresponding values, resulting in the formatted string "My name is
John and I am 30 years old."
Using f-strings (formatted string literals): This is a newer and more concise approach
introduced in Python 3.6. It allows you to embed expressions directly within curly braces
{} in the string
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.
print("Hello\nWorld!")
# Output:
# Hello
# World!
print("Hello\t\tWorld!")
# Output: Hello World!
Hello
World!
Hello World!
This is a backslash: \
She said, "Hello!"
In the first example, the \n escape sequence is used to insert a newline between "Hello" and
"World!" , resulting in the output being displayed on separate lines.
In the second example, the \t escape sequence is used to insert horizontal spacing between
"Hello" and "World!" , creating a tab-like effect.
In the third example, the double backslash \\ is used to escape the special meaning of the
backslash character itself and display it as a literal backslash within the string.
In the fourth example, the backslash \" is used to escape the double quote character and
include it within the string. Similarly, the backslash \' can be used to escape the single quote
character.
In this example, the len() function is called with the string variable message as an argument.
The returned value, which represents the number of characters in the string, is stored in the
length variable. Finally, the length is displayed using the print() function.
number = 42
string_number = str(number)
print(string_number)
print(type(string_number))
# Output: "42"
# Output: <class 'str'>
42
In this example, the variable number is assigned the value 42 . The str() function is then used
to convert number to its string representation, which is stored in the variable string_number .
By printing string_number , we can observe the output as "42" , which is the string
representation of the number 42 . To demonstrate the change in data type, the type() function
is called on string_number , and its output <class 'str'> confirms that string_number is
indeed of type string .
Memory Efficiency: When you assign a value to a variable that already holds a string,
Python tries to optimize memory usage by reusing existing string objects. It checks if the
string you are assigning already exists in memory. If it does, Python doesn't create a new
string object. Instead, it assigns the existing string object to the variable.
String Methods: String methods that seem to modify the string, such as upper() , lower() ,
or replace() , actually return a new modified string while leaving the original string
unchanged. This is important to keep in mind when working with string methods.
Hello, World!
Hi, World!
In this example, the replace() method is called on the text string to replace the substring
"Hello" with "Hi" . However, the original text string remains unchanged, and the modified string
is stored in the modified_text variable.
Key Takeaways