Matthew Habibi
Matthew Habibi

Reputation: 39

Formatting strings in python with variables

So this is my code but it returns error like this "Unknown format code 'e' for object of type 'str'". why??

c="*"*i
e=input01
d="{:>e}"
print(d.format(c))

Upvotes: 2

Views: 71

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180532

Pass e into the format as a variable, you are simply using the string "e" hence the error:

d = "{:>{e}}"
print(d.format(c, e=e))

You can see actually passing the variable right adjusts the string correctly:

In [3]: c = "*" * 4    
In [4]: e = "10"    
In [5]: d = "{:>{e}}"    
In [6]: d.format(c, e=e)
Out[6]: '      ****'

You could also remove the e from the format and pass it as the second arg to format:

d = "{:>{}}"
print(d.format(c, e))

Either way the {} after > is essential.

Upvotes: 2

Related Questions