String Formatting with %

来源:互联网 发布:2016cba选秀体测数据 编辑:程序博客网 时间:2024/05/16 08:34
String Formatting with %, Part 1

Awesome work so far. This is the last new thing to cover before we review!

We saw earlier that you can access individual characters in a string by offset, or, if you want to think about it this way, ID number. (Remember, "PYTHON"[1] is"Y", not "P"!)

Unfortunately,strings in Python are immutable—you can't change them once they're created.

However, there is a way you can work flexibility into your strings, and that's with string formatting. It uses the % symbol (don't confuse this with modulo!), and you can sort of think of it as a variable for your string.

String Formatting with %, Part 2

Did you see that? The % string formatter replaced the %s (the "s" is for "string") in our string with the variables in parentheses. (We could have done that by just putting"Camelot" and "place" in parentheses after the string, but we wanted to show you how it works with variables.)

The syntax went like this:

print "%s" % (string_variable)

You can have as many variables (or strings!) separated by commas between your parentheses as you like:

print "The %s who %s %s!" % ("Knights", "say", "Ni")

prints "The Knights who say Ni!"

name = raw_input("What is your name?")quest = raw_input("What is your quest?")color = raw_input("What is your favorite color?")print "Ah, so your name is %s, your quest is %s, " \"and your favorite color is %s." %(name, quest, color)


原创粉丝点击