COMP-122
INTRODUCTION TO
COMPUTER PROGRAMMING
Lecture 4: Strings in Python
Outline
• Introduction
• Creating String
• Formatting String Output
• String indexing and slicing
• String methods
• String Input and Output
Introduction
• A string is a sequence of characters
• String is a data type in Python for dealing with
text
• Typing string values in Python code is fairly
straightforward: they begin and end with the
quotes.
Creating a string
• A string is created by enclosing text in quotes.
You can use either single quotes, ', or double
quotes, ".
• A triple-quote can also be used for multi-line
strings:
Creating a string cont.….
• An escape character lets you use characters that
are otherwise impossible to put into a string
• An escape character consists of a backslash (\)
followed by the character you want to add to the
string:
Formatting String Output
• Format string is a way of making strings that have
variables embedded in them
• You embed variables inside a string by using a special {}
sequence and then put the variable you want inside the
{} characters.
• You must start the string with the letter f for “format,” as
in f"Hello {name}". This little f before the " and the {}
characters tell Python 3, “Hey, this string needs to be
formatted. Put these variables in there.”
Formatting String Output Cont.
• Strings in Python have also a unique built-in operation
that can be accessed with the % operator.
• This lets you do simple string positional formatting very
easily.
• Here we have used the %s format specifier to tell Python
where to substitute the value of name, represented as a
string.
Formatting String Output Cont.
• Apart from using the print f and % operator for
formatting string, python format() function has also
been introduced for handling complex string
formatting more efficiently.
• This method of the built-in string class provides
functionality for complex variable substitution and
value formatting
• The general syntax of format() method:
string.format(var1, var2, ….)
Formatting String Output Cont.
1. Using a single formatter
• Formatters work by putting in one replacement field and
placeholder defined by a pair of curly braces {} into a
string and calling the str.format() function.
• The value we wish to put into the placeholders and
concatenate with the string are passed as parameters
into the format function.
Formatting String Output Cont.
2. Using multiple formatters
• Multiple pairs of curly braces can be used while formatting the
string.
• Let’s say if another variable substitution is needed in the
sentence, can be done by adding a second pair of braces and
passing a second value into the method.
• Python will replace the placeholders with values in order
String Indexing
• Each character in a string has a numbered position
called an index
• In Python counting always starts at zero. To get the
character at the beginning of a string, you need to
access the character at position 0.
• You can access the character at the Nth position by
putting the number N in between two square brackets []
immediately after the string:
String Slicing
• A slicing is used to pick out part (substring) of a string
• It behaves like a combination of indexing and the
range function
• The basic structure is:
string name[starting location : ending location+1]
• You can leave either the starting or ending locations
blank.
String Slicing Cont.….
• There is an optional third argument, just like in
the range statement, that can specify the step.
• Steps through the string by twos, selecting the
characters at indices 0, 2, and 4.
String Methods
• Strings come with a ton of methods that return
information about the string or return a new string
that is a modified version of the original.
• Strings provide methods that perform a variety of
useful operations.
• A method is similar to a function—it takes arguments
and returns a value—but the syntax is different
String Methods Conti….
Here are some of the most useful ones:
• lower(): returns a string with every letter of the original
in lowercase
• upper(): returns a string with every letter of the
original in uppercase
• replace(x, y): returns a string with every occurrence of
x replaced by y
String Methods Conti….
• count(x): counts the number of occurrences of
x in the string
• index(x): returns the location of the first
occurrence of x
• isalpha(): returns True if every character of the
string is a letter
• isdigit() - Returns True if all characters in the
string are digits
String Methods Conti….
• startswith(x): returns True if the string value
they are called on begins with x
• endswith(x): True if the string value they are
called on ends with x
• find(x): find the location of x string in another
string
• split(): break a string into a list
String Methods Conti….
• join(): It takes a list of strings and concatenates the
elements.
• join is a string method, so you have to invoke it on the
delimiter and pass the list as a parameter:
• len(): used to determine a string’s length
String Input and Output
• Python has an input function which lets you ask a user
for some text input and then print the entered input on
the screen using print function.
1. input(prompt): To accept input from a user.
2. print(): To display output on the
console/screen.