Python Strings
Python Strings
• 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
• 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
• 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.
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
# 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
• 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"
# Exercise 2
# Store a floating-point number as a string
my_float_string = "6.01"
# 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.
# 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:
• Replace String:
# 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
print(my_text)