Helpful Information
 
 
Category: Python Programming
In python, how do you put variables in strings?

It should be very simple, but I seem to be missing it. In perl it would look like this:

$name = (whatever name you input)
$age = (again, whatever you input previously)

then you could display it like:

print "Hello $name, you are $age years old."

I know python could do

print "Hello",name,"you are",age,"years old."

But that doesnt cut it, since it always adds spaces.

print "Hello",name,"!"

whould print:

Hello Jack !

Dont ask me why python forces spaces in there.. is there anyway to just call variables within strings like in perl?

It is very simple: Just use string format characters (http://python.org/doc/current/lib/typesseq-strings.html).

In this example:
print 'Hello %s, you are %s years old.' % (name, age)

You could also use string concatenation like this:
print 'Hello '+name+', you are '+age+' years old.'
But this is slower, and IMO less readable.

why can't you use %u instead of %s?

User input from terminal changed between python2 and python3. This method works in both versions:

import sys

sys.stdout.write('OK? (y/n) ')
user_input = sys.stdin.readline()
if 'y' == user_input[0].lower():
ok_action()
else:
no_go()

name = 'Frank'
age = 12

# vars() is the local dictionary containing variables name and age as keys
print("Hello %(name)s, you are %(age)s years old." % vars())

''' result -->
Hello Frank, you are 12 years old.
'''

A little bit more old-fashioned:

import string

name = "Frank"
age = 12

# variables to be substituted begin with a $
t = string.Template("Hello $name, you are $age old!")
# local disctionary vars() contains variables name and age
s = t.substitute(vars())
print(s)

''' result -->
Hello Frank, you are 12 old!
'''

If you have Python273 or Python3, you can use:

name = 'Frank'
age = 12

# vars() is the local dictionary containing variables name and age as keys
# needs Python273 or Python3 and higher
print("Hello {name}, you are {age} years old.".format(**vars()))


''' result -->
Hello Frank, you are 12 years old.
'''










privacy (GDPR)