0% found this document useful (0 votes)
13 views

String

The document discusses strings in Python, including how to create string variables, concatenate strings using the + operator, index and slice strings using brackets, and extract substrings from a string.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

String

The document discusses strings in Python, including how to create string variables, concatenate strings using the + operator, index and slice strings using brackets, and extract substrings from a string.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

4/25/24, 10:29 PM Notebook.

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.

keyboard_arrow_down Creating String variables


To work with strings in Python, you can assign them to variables. Variables act as containers
that store data, including strings. Here's an example of creating a string variable:

message = "Hello, Python!"


print(message)

Hello, Python!

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 1/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

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!" .

String variables can also be created using single quotes:

name = 'John Doe'


print(name)

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.

You can also assign an empty string to a variable:

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.

keyboard_arrow_down String Concatenation


String concatenation is the process of combining two or more strings together. In Python, you
can concatenate strings using the + operator. When you use the + operator with strings, it
merges them into a single string.

Here's an example of string concatenation:

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 .

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 2/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

You can also concatenate string literals directly without using variables:

greeting = "Hello" + ", " + "World!"


print(greeting)

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.

keyboard_arrow_down String Indexing and Slicing


Strings in Python are ordered sequences of characters, which means that each
character in a string has a specific index associated with it.

String indexing allows you to access individual characters within a string.

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:

message = "Hello, World!"


print(message[0]) # Output: H
print(message[7]) # Output: W

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

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 3/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

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.

Here's an example of string slicing:

message = "Hello, World!"


print(message[0:5]) # Output: Hello
print(message[7:12]) # Output: World

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:

Slicing from the beginning

text = "Hello, World!"


print(text[:5])
# Output: "Hello"

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" .

Slicing to the end

text = "Hello, World!"


print(text[7:])
# Output: "World!"

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!" .

slicing with start and end indices

text = "Hello, World!"


print(text[2:7])
# Output: "llo, "

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 4/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

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, " .

Slicing with step value

text = "Hello, World!"


print(text[::2])
# Output: "Hlo ol!"

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!" .

text = "Hello, World!"


print(text[1:10:2])
# Output: "el,Wr"

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" .

Here's a breakdown of the slicing steps:

The character at index 1 is included: "e"


The character at index 3 is included: "l"
The character at index 5 is included: ","
The character at index 7 is included: "W"
The character at index 9 is included: "r"

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.

keyboard_arrow_down Common indexing and slicing errors


Index Out of Range

text = "Hello, World!"


print(text[20])

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 5/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

---------------------------------------------------------------------------
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).

keyboard_arrow_down Using a Floating-Point Index


text = "Hello, World!"
print(text[2.5])

---------------------------------------------------------------------------
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.

keyboard_arrow_down Slicing with Invalid Step


text = "Hello, World!"
print(text[::0])

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 6/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

---------------------------------------------------------------------------
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.

keyboard_arrow_down String Methods


Python provides several built-in methods that allow you to perform various operations on strings.
These methods enable you to modify and manipulate strings in different ways. Let's explore
some commonly used string methods:

upper() : Converts all characters in a string to uppercase

message = "Hello, World!"


print(message.upper()) # Output: HELLO, WORLD!

HELLO, WORLD!

lower() : Converts all characters in a string to lowercase

message = "Hello, World!"


print(message.lower()) # Output: hello, world!

hello, world!

capitalize() : Capitalizes the first character of a string and converts the remaining
characters to lowercase

message = "hello, world!"


print(message.capitalize()) # Output: Hello, world!

Hello, world!

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 7/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

title() : Capitalizes the first character of each word in a string

message = "hello, world!"


print(message.title()) # Output: Hello, World!

Hello, World!

strip() : Removes leading and trailing whitespace from a string

message = " Hello, World! "


print(message.strip()) # Output: "Hello, World!"

Hello, World!

replace(old, new) : Replaces all occurrences of a specified substring with a new


substring

message = "Hello, World!"


new_message = message.replace("World", "Python")
print(new_message) # Output: Hello, Python!

Hello, Python!

split(separator) : Splits a string into a list of substrings based on a specified separator

message = "Hello, World!"


split_message = message.split(",")
print(split_message) # Output: ['Hello', ' World!']

['Hello', ' World!']

keyboard_arrow_down String Formatting


String formatting allows you to create dynamic strings by incorporating variables or values into
pre-defined string templates. Python provides multiple ways to format strings, including:

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.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 8/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

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.

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.

My name is John and I am 30 years old.

F-strings provide a concise and readable way to format strings by directly


embedding expressions within the string, making the code more straightforward
and less error-prone.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Noteboo… 9/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

keyboard_arrow_down String Escape Sequences


In Python, escape sequences are special characters that are used to represent certain
characters that cannot be easily typed or displayed directly within a string. Escape sequences
are denoted by a backslash ( \ ) followed by a specific character or combination of characters.

Here are some commonly used escape sequences:

\n : Represents a newline character and is used to start a new line


\t : Represents a tab character and is used to create horizontal spacing
\\ : Represents a backslash character and is used to display a literal backslash
\" or \' : Represents a double quote or a single quote character, respectively, and is used
to include these characters within a string when using the corresponding quotation marks

Here are some examples:

print("Hello\nWorld!")
# Output:
# Hello
# World!

print("Hello\t\tWorld!")
# Output: Hello World!

print("This is a backslash: \\")


# Output: This is a backslash: \

print("She said, \"Hello!\"")


# Output: She said, "Hello!"

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.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Notebo… 10/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

keyboard_arrow_down Working with String Operations


Length of a String
To determine the length of a string in Python, you can use the built-in len() function. The len()
function returns the number of characters in a string. Here's an example:

message = "Hello, World!"


length = len(message)
print("The length of the string is:", length)
# Output: The length of the string is: 13

The length of the string is: 13

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.

keyboard_arrow_down Converting other data types to strings


In Python, you can convert data between strings and other data types using built-in functions.
These functions allow you to convert values from one data type to another, providing flexibility in
data manipulation and representation. The str() function converts a value to its string
representation.

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 .

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Notebo… 11/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

keyboard_arrow_down String Immutability


In Python, strings are immutable, which means that once a string is created, its
contents cannot be changed. This immutability property has several implications
and considerations when working with strings.

Creating a new String: Whenever you perform an operation that appears to


modify a string, such as concatenation or replacing characters, it actually
creates a new string with the desired changes. The original string remains
unchanged.

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.

Understanding Assignments: Assigning a new value to a string variable replaces the


reference to the original string with a reference to the new string. It does not modify the
original string in-place.

Here's an example to illustrate the immutability of strings:

text = "Hello, World!"


modified_text = text.replace("Hello", "Hi")
print(text) # Output: "Hello, World!"
print(modified_text) # Output: "Hi, World!"

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

Strings are a data type used to represent textual data in Python


They are created by enclosing text within single quotes ( '...' ) or double quotes ( "..." )
Strings are sequences of characters, and each character has an index starting from 0
Indexing allows accessing individual characters in a string using their position

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Notebo… 12/13


4/25/24, 10:29 PM Notebook.ipynb - Colab

Slicing enables extracting a portion of a string by specifying a range of indices


String concatenation combines multiple strings into a single string
String methods provide built-in functionality to manipulate and modify strings
Common string methods include upper() , lower() , capitalize() , and replace()
These methods return new modified strings while leaving the original string unchanged
String formatting allows inserting dynamic values into a string using placeholders
Escape sequences allow representing special characters within strings
Examples of escape sequences include \n for a new line, \t for a tab, and \" for a
double quote
Strings in Python are immutable, meaning they cannot be changed once created
Modifying a string actually involves creating a new string with the desired changes

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/4. Strings/Notebo… 13/13

You might also like