Variable inside python format specifier [duplicate] - python

This question already has an answer here:
How to pad numbers with variable substitution for padding width in format or f string? [duplicate]
(1 answer)
Closed 7 months ago.
I am wondering whether I can add a variable inside the f string to specify the width of item to be printed.
For example:
print("{:>5}".format("cat"))
In the example how can I replace 5 with a variable that can change at runtime.

inside the f string
Be careful using the term "f string" -- you're talking about a format string whereas an f-string is a feature of the latest releases of Python and something different, but related:
animal = 'cat'
pad = 5
print(f"{animal:>{pad}}")
Otherwise, if you just want a format string without the f-string, then #JohnnyMopp's comment (+1) shows the correct syntax.

Here is how:
a = 5
print("{:>"f"{a}""}".format("cat"))
Output:
cat
You can also do that using str.rjust():
a = 5
print("cat".rjust(a))
Output:
cat

Related

How to interpret a string as code in Python [duplicate]

This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 7 months ago.
How to make a function that can interpret a string as a code ?
var1 = 5
var2 = 10
var3 = 7
str = "(var1*var2)+var3"
result = calculate(str) # I need help to write this function
result should output 57
Use result = eval(str) instead of result = calculate(str).
Disclaimer: eval() should be used carefully since it can execute anything passed to it. More details can be found in this article.

Not too sure about replace() function on Python - why isn't dog being replaced with cat? [duplicate]

This question already has answers here:
python: why does replace not work?
(2 answers)
Closed 1 year ago.
a = 'dog'
a.replace('dog', 'cat')
print (a)
Really basic question, the function seems to be fairly straightforward but it just isn't replacing in this instance for some reason - is it because replace doesn't inherently change "a"?
Yes, you are correct. It won’t modify a.
Replace function will return a replaced string.
So, if you like to replace the text in a. Use the below code.
a = 'dog'
a = a.replace('dog', 'cat')
print (a)
Strings are immutable data types in Python which means that its value cannot be updated. Variables can point at whatever they want.
str.replace() creates a copy of string with replacements applied. See documentation.
Need to assign a new variable for the replacement.
a = 'dog'
b = a.replace('dog', 'cat')
print(b)
Output:
cat

Replace word in string using f-string [duplicate]

This question already has answers here:
How to postpone/defer the evaluation of f-strings?
(14 answers)
Closed 2 years ago.
In Python, I'm trying to insert a variable into an imported string that already contains the variable name - as pythonically as possible.
Import:
x = "this is {replace}`s mess"
Goal:
y = add_name("Ben", x)
Is there a way to use f-string and lambda to accomplish this? Or do I need to write a function?
Better option to achieve this will be using str.format as:
>>> x = "this is {replace}`s mess"
>>> x.format(replace="Ben")
'this is Ben`s mess'
However if it is must for you to use f-string, then:
Declare "Ben" to variable named replace, and
Declare x with f-string syntax
Note: Step 1 must be before Step 2 in order to make it work. For example:
>>> replace = "Ben"
>>> x = f"this is {replace}`s mess"
# ^ for making it f-string
>>> x
'this is Ben`s mess' # {replace} is replaced with "Ben"

Leave empty spaces with format while printing an String in python [duplicate]

This question already has answers here:
How to print a string at a fixed width?
(7 answers)
Closed 2 years ago.
I have created a program.Here I need to leave some space and print an String after the spaces.I did that program with format in python.my code is below,
name = "myname"
print("{0:>10}".format(name))
#output=" myname"
Here, the sum of empty spaces and the length of name is equals to 10.I have declared the size inside print.
But I need to declare the size as a variable.I tried it like this,
num = 10
name = "myname"
print("{0:>num}".format(name))
but it did not worked.I need to know how I can fix this.I need to take the same output with giving the size with an variable.please help...
Try this one:
num_of_spaces = 10
name = "myname"
name.rjust(num_of_spaces)
Try:
num = 10
name ="myname"
print(" "*num,name)
Or you can also do it via:
name ="myname"
print('{0} {1}'.format(' '*num,name))

How to add comma in print statement in Python [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
Closed 5 years ago.
I'm new to python and learning how to code.
I'm printing last element of my list and sum of the list as-
print list[-1],sum
But the output is separated by " " and not separated by ",".
Any idea how to separate it by comma?
I'm using Python 2.7
Include it in quotes, like this:
print str(list[-1]) + "," + str(sum)
Enclosing them in str() is unnecessary if list[-1] and sum are strings.
In general, symbols are interpreted as Python symbols (for example, names like sum are interpreted as variable or function names). So whenever you want to print anything as is, you need to enclose it in quotes, to tell Python to ignore its interpretation as a Python symbol. Hence print "sum" will print the word sum, rather than the value stored in a variable called sum.
You'll have to compose that together into a string. Depending on what version of Python you're using, you could either do:
print "{},{}".format(list[-1], sum)
or
print "%s,%s" % (list[-1], sum)
If you were using Python3.6+, there would be a third option:
print(f"{list[-1]},{sum}")
Use the sep keyword argument:
print(list[-1], sum, sep=',')
You can use str.format() and pass whatever variables you want to get it formatted, for example:
x = 1
z = [1, 2, 3]
y = 'hello'
print '{},{},{}'.format(x, z[-1], y)
# prints: 1,3,hello

Categories