0% found this document useful (0 votes)
23 views47 pages

Python Strings

The document provides an overview of strings in Python, including their properties, how to create and manipulate them, and common operations such as concatenation, indexing, and slicing. It also covers string methods for case conversion, whitespace removal, and user input interaction, along with exercises for practical application. Additionally, it discusses converting between strings and numbers, formatted string literals (f-strings), and finding and replacing substrings.

Uploaded by

upeshpatel.ec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views47 pages

Python Strings

The document provides an overview of strings in Python, including their properties, how to create and manipulate them, and common operations such as concatenation, indexing, and slicing. It also covers string methods for case conversion, whitespace removal, and user input interaction, along with exercises for practical application. Additionally, it discusses converting between strings and numbers, formatted string literals (f-strings), and finding and replacing substrings.

Uploaded by

upeshpatel.ec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Strings

Dr. Upesh Patel & Dr. Trushit Upadhyaya


CHAROTAR UNIVERSITY OF SCIENCE & TECHNOLOGY
What is a String?
• Strings are one of the fundamental Python data types. - they can’t
be broken down into smaller values of a different type.
• The term data type refers to what kind of data a value represents.
• Strings are used to represent text
• string data type has a special abbreviated name in Python: str
• You can see this by using the type( ) function e.g.
Strings properties
• Strings contain characters, which are individual letters or
symbols

• Strings have a length, which is the number of characters contained


in the string

• Characters in a string appear in a sequence, meaning each


character has a numbered position in the string
String Literals (or String)
• Whenever you create a string by surrounding text with quotation
marks, the string is called a string literal.
• Either single quotes (string1) or double quotes (string2) can be
used to create a string, as long as both quotation marks are the
same type.

• The quotes surrounding a string are called delimiters because they


tell Python where a string begins and where it ends. When one type
quotes is used as the delimiter, the other type of quote can be used
inside of the string.
Common Error
Multiline Strings
• The PEP 8 style guide recommends that each line of Python code
contain no more than 79 characters—including spaces.
• To deal with long strings, you can break the string up across multiple
lines into a multiline string. For example, suppose you need to fit
the following text into a string literal.
• When you print ( ) a multiline string that is broken up by backslashes,
the output displayed on a single line:
Quick Recap – Hands on Exercise
• Print a string that uses double quotation marks inside the
string.
• Print a string that uses an apostrophe inside the string.
• Print a string that spans multiple lines, with whitespace
preserved.
• Print a string that is coded on multiple lines but displays on a
single line.
Concatenation, Indexing, and
Slicing
String Concatenation
• Two strings can be combined, or concatenated, using the +
operator

Output for both codes?


String Indexing
• Each character in a string has a numbered position called an index.
You can access the character at the Nth position by putting the number N in
between two square brackets ([ and ]) immediately after the string.

• 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

Forgetting that counting starts with zero and trying to access the first
character in a string with the index 1 results in an off-by-one error
String Indexing

• The following figure shows the index for each character of the string
"apple pie":

• If you try to access an index beyond the end of a string, Python raises
an IndexError. The largest index in a string is always one less than the
string’s length
Negative Indices
• Strings also support negative indices

• Just like positive indices, Python raises an IndexError if you try to


access a negative index less than the index of the first character in
the string.
• One way to get the last character of a string is to calculate the final
index using len( )
String Slicing
• Suppose you need the string containing just the first three letters of
the string "apple pie". You could access each character by index and
concatenate them

• Alternatively, You can extract a portion of a string, called a substring, by


inserting a colon between two index numbers inside of square brackets

• The [0:3] part of flavor[0:3] is called a slice.


Slicing Variants
• The slice [x:y] returns the substring between the boundaries x and y.
So, for "apple pie", the slice [0:3] returns the string "app", and the slice
[3:9] returns the string "le pie"

• The first line gets the slice from the beginning of the string up to but not
including the fourteenth character. The string assigned to flavor has length
nine, so you might expect Python to throw an error. Instead, any non-
existent indices are ignored and the entire string "apple pie" is returned.
• flavor[13:15] attempts to get the thirteenth and fourteenth characters,
which don’t exist. Instead of raising an error, the empty string "" is
returned.
Negative Indices in Slicing

Guess the output


Strings Immutable Property
• Strings are immutable, which means that you can’t change them
once you’ve created them.

• Quick Recall: The term str is Python’s internal name for the string
data type.
• Quick Exercise : Change the string goal to foal.
Quick Recap – Hands on Exercise
• Create a string and print its length using the len() function.

• Create two strings, concatenate them, and print the resulting


string.

• Create two strings and use concatenation to add a space in between


them. Then print the result.

• Print the string "zing" by using slice notation on the string


"bazinga" to specify the correct range of characters.
String Manipulation
• Strings come bundled with special functions called string
methods that can be used to work with and manipulate strings.
Converting String Case

Removing Whitespace From a String

1. .rstrip()
2. .lstrip()
3. .strip()
String Manipulation
• Determine if a String Starts or Ends With a Particular String
to determine if a given string starts with or ends with certain
characters : .startswith() and .endswith()
Quick Recap – Hands on Exercise
• Write a script that converts the following strings to lowercase: "Animals", "Badger",
"Honey Bee", "Honeybadger". Print each lowercase string on a separate line.
• Repeat Exercise 1, but convert each string to uppercase instead of lowercase.
• Write a script that removes whitespace from the following strings. Print the strings
with the whitespace removed.

• Write a script that prints out the result of .startswith("be") on each of the
following strings

• Using the same four strings from Exercise 4, write a script that uses string methods
to alter each string so that .startswith("be") returns True for all of them
User Input Interaction
• The input() function

• Playing with User Input:


Quick Recap – Hands on Exercise
• Write a script that takes input from the user and displays that
input back.
• Write a script that takes input from the user and displays the input
in lowercase.
• Write a script that takes input from the user and displays the
number of characters inputted.
# Exercise 1
# Take input from the user and display that input back
my_input = input("Type something: ")
print(my_input)

# Exercise 2
# Display the input string converted to lower-case letters
print(my_input.lower())

# Exercise 3
# Take user input and display the number of input characters.
input_string = input("Type something else: ")
print(len(input_string))
Fun Challenge : Pick Apart Your User’s Input
• Write a script named first_letter.py that first prompts the user for
input by using the string "Tell me your password:" The script
should then determine the first letter of the user’s input, convert
that letter to upper-case, and display it back. For example, if the
user input is "no" then the program should respond like this:
The first letter you entered was: N
• # Return the upper-case first letter entered by the user

• user_input = input("Tell me your password: ")


• first_letter = user_input[0]
• print("The first letter you entered was: " + first_letter.upper())
Working With Strings and Numbers
• When you get user input using the input() function, the result is always a
string. There are many other times when input is given to a program as a
string. Sometimes those strings contain numbers that need to be fed into
calculations.
• Strings and Arithmetic Operators

The + operator concatenates two string together

Strings can be “multiplied” by a number as long as that number is an integer, or


whole number. Try following in the IDLE.
Strings and Arithmetic Operators
• Try following item in IDLE
• You can’t multiply a sequence by a non-integer.
• When the * operator is used with a string
on either the left or the right side, it always expects an integer on the
other side. A sequence is any Python object that supports accessing
elements by index. Strings are sequences.
• Try following item in IDLE

• the + operator expects both things on either side of it to be of the same


type .
Converting Strings to Numbers
• Try following script:

• int() stands for integer and converts objects into whole numbers,
while float() stands for сoating-point number and converts
objects into numbers with decimal points.
• Try following in the IDLE: int("12") and float ("12").
• Also try, int("12") – Python shall not change 12.0 into 12 because
it would result in the loss of precision
Converting Strings to Numbers
The Conversion:
Converting Numbers to Strings

OR
Quick Recap – Hands on Exercise
• Create a string containing an integer, then convert that string into an
actual integer object using int(). Test that your new object is a number by
multiplying it by another number and displaying the result.

• Repeat the previous exercise, but use a floating-point number and float().
• Create a string object and an integer object, then display them sideby-side
with a single print statement by using the str() function.
• Write a script that gets two numbers from the user using the input()
function twice, multiplies the numbers together, and displays the result. If
the user enters 2 and 4, your program should print the following text: The
product of 2 and 4 is 8.0
# Exercise 1
# Store an integer as a string
my_integer_string = "6"

# Convert the 'integer' string into an int object using int()


# Multiply the integer by 7 and display the result
print(int(my_integer_string) * 7)

# Exercise 2
# Store a floating-point number as a string
my_float_string = "6.01"

# Convert the 'float' string into a number using float()


# Multiply the number by 7 and display the result
print(float(my_float_string) * 7)
• # Exercise 3
# Create a string and an int object, then display them together
my_string = "mp"
my_int = 3
print(my_string + str(my_int))

# Exercise 4
# Get two numbers from the user, multiply them,
# and display the result
a = input("Enter a number: ")
b = input("Enter another number: ")
product = float(a) * float(b)
print("The product of " + a + " and " + b + " is " + str(product) + ".")
Streamline Print Statements
• Suppose you have a string name = "Zaphod" and two integers heads = 2
and arms = 3. You want to display them in the following line: Zaphod has
2 heads and 3 arms. This is called string interpolation.

OR

Both techniques produce code that can be hard to read. Trying to keep
track of what goes inside or outside of the quotes can be tough. There’s
a third way of combining strings: formatted string literals, more
commonly known as f-strings
f-strings (formatted string literals)
• There are two important things to notice about the above examples:
1. The string literal starts with the letter f before the opening
quotation mark.
2.Variable names surrounded by curly braces ({ and }) are replaced
with their corresponding values without using str()
• Python expressions can also be inserted in between the curly
braces. The expressions are replaced with their result in the string.

Python 3.6 and above

Available in older version


Quick Recap – Hands on Exercise
• Create a float object named weight with the value 0.2, and create
a string object named animal with the value "newt". Then use
these objects to print the following string using only string
concatenation: 0.2 kg is the weight of the newt.
• Display the same string by using the .format() method and empty
{} place-holders.
• Display the same string using an f-string.
# Exercise 1
weight = 0.2
animal = "newt"

# Concatenate a number and a string in one print call


print(str(weight) + " kg is the weight of the " + animal + ".")

# Exercise 2
# Use format() to print a number and a string inside of another string
print("{} kg is the weight of the {}.".format(weight, animal))

# Exercise 3
# Use formatted string literal (f-string) to reference objects inside a string
print(f"{weight} kg is the weight of the {animal}.")
Find a String in a String
• One of the most useful string methods is .find(). As its name
implies, you can use this method to find the location of one string
in another string—commonly referred to as a substring.
• To use .find(), tack it to the end of a variable or a string literal and
pass the string you want to find in between the parentheses.

• The value that .find() returns is the index of the first occurrence of
the string you pass to it. In this case, "surprise" starts at the fifth
character of the string "the surprise is in here somewhere" which
has index 4 because counting starts at 0
Find a String in a String
• If .find() doesn’t find the desired substring, it will return -1 instead. Try in
IDLE
• You can call string methods on a string literal directly, so in this case,
you don’t need to create a new string:

• Keep in mind that this matching is done exactly, character by character,


and is case-sensitive. For example, if you try to find "SURPRISE",
the .find() method returns -1.
• If a substring appears more than once in a string, .find() only
returns the index of the first appearance, starting from the
beginning of the string. Try in IDLE.
• The .find() method only accepts a string as its input. If you want to
find an integer in a string, you need to pass the integer to .find() as
a string.
Playing with the string continued

• Replace String:

• Since strings are immutable objects, .replace() doesn’t alter


my_story. To change the value of my_story, you need to reassign to
it the new value returned by .replace().
Quick Recap – Hands on Exercise
• In one line of code, display the result of trying to .find() the
substring "a" in the string "AAA". The result should be -1.
• Replace every occurrence of the character "s" with "x" in the string
"Somebody said something to Samantha.".
• Write and test a script that accepts user input using the input()
function and displays the result of trying to .find() a particular
letter in that input.
# Exercise 1
# Cannot find the string "a" in the string "AAA":
print("AAA".find("a"))

# Exercise 2
# Replace every occurrence of the character `"s"`
# with the character `"x"`
phrase = "Somebody said something to Samantha."
phrase = phrase.replace("s", "x")
print(phrase)
# NOTE: This leaves the capital "S" unchanged, so the
# output will be "Somebody xaid xomething to Samantha."

# Exercise 3
# Try to find an upper-case "X" in user input:
my_input = input("Type something: ")
print(my_input.find("X"))
Fun Challenge: Turn Your User Into a L33t H4x0r
• Write a script called translate.py that asks the user for some input prompt:
Enter some text:. Then use the .replace() method to convert the text entered
by the user into “leetspeak” by making the following changes to lower-case
letters
• The letter e becomes 3
• The letter l becomes 1
• The letter o becomes 0
• The letter s becomes 5
• The letter t becomes 7

Your program should then display the resulting string as output. Below is a
sample run of the program:
# Turn a user's input into leetspeak

my_text = input("Enter some text: ")

my_text = my_text.replace("a", "4")


my_text = my_text.replace("b", "8")
my_text = my_text.replace("e", "3")
my_text = my_text.replace("l", "1")
my_text = my_text.replace("o", "0")
my_text = my_text.replace("s", "5")
my_text = my_text.replace("t", "7")

print(my_text)

You might also like