Manipulating Strings

What are strings?

Any sequence of characters enveloped in quotes (single, double, triple). Your opening quotes need to match your closing quotes.

String literals:

"this is a string"
'this is also a string'

Use variable names:

my_name = "Julia Smith"

Concatenate strings

Use the + operator to “glue” strings together:

message = "Hi there"
punctuation = "!"
print(message + punctuation)
Hi there!

You can also use += to change to retrieve the string assigned to a variable, “glue” another string to it, and assign it back to the same variable name:

full_message = "" # start with an empty string
full_message += "Hi there"
full_message += "!"
print(full_message)
Hi there!

Writing your own function

Use the keyword def to define a function use () after your function name to list all the parameters.

def repeat_message(message, n):
  full_message = message * n
  return full_message

message = repeat_message("Hi there", 5)
print(message)
Hi thereHi thereHi thereHi thereHi there
  • What if I wanted to have a space between each string?
  • What if I wanted to have a line break between each string?

Short Project

Instructions for Short Project of the Week