We've already learned one way to put together strings. What is it? →
String formatting allows you to put placeholders in your string where values should go. One way to this is to use the % operator (there's a more modern syntax, but you'll still see this a lot):
s = "string"
print("this is a %s" % (s))
lyrics = "you can get with %s or you can get with %s"
s1 = "this"
s2 = "that"
print(lyrics % (s1, s2))
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)
Both string concatenation and string formatting evaluate to a value - specifically a string! That means:
As for print()
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))