Strings#

We’ve encountered Python’s string data type before- we can use indexing to think of a string as a collection of values (even if it’s not officially a linear array).

String Basics#

# creating a string variable
x = "Hello World!"

# checking data type
type(x)
# converting to a string data type
y = 7
y = str(y)

# checking data type
type(y)

Indexing#

Because strings in Python are indexed, we can access specific values based on their position (or place/location).

# return number of characters in string
len(message)

# access first character in string
message[0]

# access last character in string
message[-1]

Concatenation#

Remember we can use concatenation to join or combine string objects.

# first and last name variables
first = "Knute"
last = "Rockne"

# use concatenation to create full name
name = first + " " + last
print(name)

Additional String Methods#

Python includes a number of built-in methods we can use to interact with strings. Brief explanations and examples are provided in each section.

Capitalizing#

We can change a string’s capitalization using the following methods:

  • .title() (title case)

  • .upper()(upper case)

  • .lower() (lower case)

# create name variable
name = "Knute Rockne

# print in title case
print(name.title())

# print in lower case
print(name.lower())

# print in upper case
print(name.upper())

Searching#

We can search for values in a string using the following methods:

  • .count() (returns number of times specific value appears in a string)

  • .startswith() (returns Boolean True/False value if string begins with specific value

  • .endswith() (returns Boolean True/False value if string ends with specific value)

  • .find() (returns index for specific value in string, searching left-to-right)

  • .rfind() (returns index for specific value in string, searching right-to-left)

  • .index() (returns index for specific value in string)

  • .rfind() (returns index for specific value in string, searching right-to-left)

# create color variable
color = "chartreuse"

# return number of e characters in string
print(color.count("e"))

# return true/false if string begins with value
print(color.startswith("e")) # returns false

# return true/false if string ends with value
print(color.endswith("e")) # returns true

# returns position for first occurance of value in the string
print(color.find("e")) # returns 6

# returns index for first occurance of value in the string
print(color.index("e")) # returns 6

# returns position for first occurance of a value in the string searching right-to-left
print(color.rfind("e")) # returns 1

# returns index for first occurance of a value in the string searching right-to-left
print(color.rindex("e")) # returns 1

We can also use these methods to search for a substring within a string.

# create string variable
passage = "As there is no other school within more than a hundred miles, this college cannot fail to succeed. Before long, it will develop on a large scale. It will be one of the most powerful means for good in this country."

# return true/false if string ends with substring
print(passage.endswith("good")) # returns false

# returns position for first occurance of substring
print(passage.find("college"))

Modifying#

Strings in Python are immutable- that is values in the string cannot be modified once it has been created and assigned to a variable. But Python include string methods that facilitate modifying a string to create a new string object.

  • .replace() replaces a value in a string. Syntax: .replace("OLD VALUE", "NEW VALUE")

  • .split() splits a string at a specific separator and returns a list. The default separator is a space or whitespace character. Syntax: .split("SEPARATOR")

  • .strip() trims specific character(s) from a string. The default character .strip() removes is a whitespace character. Syntax: .strip("CHARACTERS TO STRIP")

# create string variable
passage = "As there is no other school within more than a hundred miles, this college cannot fail to succeed. Before long, it will develop on a large scale. It will be one of the most powerful means for good in this country."

# replace value in string
modified = passage.replace("cannot", "can't")
print(modified)

# split string at separator
sentences = passage.split(". ")
print(sentences)

# remove strip whitespace from string
modified = passage.strip()
print(modified)

Testing for Membership#

We can also test for membership using the in operator.

# test if character x is in string
'x' in message # returns false

# test if symbol % is NOT in string
'%' not in message # returns true

Comprehension Check#

Clipboard icon Strings in Python Comprehension Check

Application Questions#

Q1: Write a program that converts integer, float, or boolean values to a string, using the str() function.

Q2: Write a program that prompts the user to enter a 6-letter word, and then prints the first, third, and fifth letters of that word.

Q3: Modify the program provided below to search for the character q or u in the string. Does it always return the index number you expect? What index is returned if you ask for the index of the letter u (i.e., what happens when the desired character appears more than once in the string)?

# program you're modifying
# assign string variable
color = "turquoise"

# get index number of t character
index_number = color.index("t")

# show index number as part of print statement
print ("The index number for the letter t within the word " + color + " is " + index_number)