nuggetinu
nuggetinu

Reputation: 23

Trying to replace a normal var with % in a print statement

Basically I'm learning some python basics and without issues executed the below:

print(var1 + ' ' + (input('Enter a number to print')))

Now I'm trying to print the output of the variable along with the string stating "You have entered" using the % method.

Have tried this apart from other code: print(%s + ' ' + (input('Enter a number to print')) %(var)) but gives a syntax error on the %s

Upvotes: 1

Views: 1238

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

Don't. This way of formatting strings is from python 2.x and there are far batter ways to deal with string formatting in python 3.x:


Your code has 2 problems:

print(var1 + ' ' + (input('Enter a number to print')))

is, if var1 is a string it works - if not it crashes:

var1 = 8
print(var1 + ' ' + (input('Enter a number to print')))

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(var1 + ' ' + (input('Enter a number to print')))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

You could do

var1 = 8
print(var1 , ' ' + (input('Enter a number to print')))

but then you lost the ability to format var1. Also: the input is evaluated before the print, so its text is on one line, followed by the print-statements output - why put them into the same line then?

Better:

var1 = 8

# this will anyhow be printed in its own line before anyway
inp = input('Enter a number to print')

# named formatting (you provide the data to format as tuples that you reference
# in the {reference:formattingparams}
print("{myvar:>08n} *{myInp:^12s}*".format(myvar=var1,myInp=inp))

# positional formatting - {} are filled in same order as given to .format()
print("{:>08n} *{:^12s}*".format(var1,inp))

# f-string 
print(f"{var1:>08n} *{inp:^12s}*")

# showcase right align w/o leading 0 that make it obsolete
print(f"{var1:>8n} *{inp:^12s}*")

Output:

00000008 *   'cool'   *
00000008 *   'cool'   *
00000008 *   'cool'   *
       8 *   'cool'   *

The mini-format parameters mean:

:>08n    right align, fill with 0 to 8 digits (which makes the > kinda obsolete)
         and n its a number to format

:^12s    center in 12 characters, its a string

Have a look at print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) as well. It has several options to control the output - f.e. what to use as seperator if multiple things are given:

print(1,2,3,4,sep="--=--") 
print(  *[1,2,3,4], sep="\n")  # *[...] provides the list elemes as single params to print

Output:

1--=--2--=--3--=--4

1
2
3
4

Upvotes: 1

khelwood
khelwood

Reputation: 59185

Perhaps you mean something like this:

print('%s %s'%(var1, input('Enter a number to print')))

The %s goes inside the quotes, and indicates the position of the elements you want to insert in the string.

Upvotes: 1

Related Questions