String Formatting

Putting Strings Together

We've already learned one way to put together strings. What is it? →

There's Also String Formatting

String formatting allows you to put placeholders in your string where values should go.

s = "string"
print("this is a %s" % (s))

Multiple Values

lyrics = "you can get with %s or you can get with %s"
s1 = "this"
s2 = "that"
print(lyrics % (s1, s2))

String Formatting

What was it again?

Allowing placeholders in a string to accommodate variable / value substitution.

#  note the use of variables... 
#  string formatting doesn't have to consist of string literals!
#  values don't have to be strings!?
greeting = "Hi.  My name is %s and I have %s %s"
name = "Joe"
number_of_pets = 314
pet = "aardvarks"
result = greeting % (name, number_of_pets, pet)
print(result)

A Closer Look at String Formatting

When to Use String Formatting

So, What Does print() Do?

Both string concatenation and string formatting evaluate to a value - specifically a string! That means:

As for print()

Greetings (Revisited)

Write a program that asks for the user's name. The program will print out "Hello (name)" using string formatting. →

What's your name?
>Joe
Hello Joe!
name = input('What\'s your name?\n>')
print("Hello %s" % (name))

And Mistakes Were Made

Built-In Modules In Depth!