String formatting with %, Part 1


#1

I am kinda confused with the difference between variable and string?

When we set the variable "spam" equals to food, we can represent it as
spam=food

but why in this page, they display
string_1= "Camelot" ?

Why are there quotation marks on Camelot?


#2

@gpvlr45
Well I do not think you are getting it right.

When you use string formatting you can build some nice things with them.

Example

print("I like %s" % 'fish')

or

holder = ["I like %s"]
print(holder[0] % 'fish')

Both of these will print out "I like fish", while they are both different in implementation both use the same principal of inserting in something, this something is called a variable. String formatting allows us to substitute specific keyword strings for our variable so we can change the output depending on what we need.

EXAMPLE:

def get_word():
    return raw_input("Enter a word!")

def print_statement(word):
    return "Hello, this is your word: %s" % word

print(print_statement(get_word()))

using string formatting also allows you to do other fancy stuff,

Example:

file = raw_input("What do you want to name this file?")
with open("%s.txt" % file, "w+")  as file_open:
    file_open.writeline(file)

There are tons of other things you can do with it that you will come into contact with latter so get excited!


#3