11

Here is a simple example

amount1 = input("Insert your value: ")
amount2 = input("Insert your value: ")
print "Your first value is", amount1, "your second value is", amount2

This is ok, but I would like to know if there is another method to include the variable in the string without concatenation or a comma.

Is this possible?

0

3 Answers 3

19

Use string formatting:

s = "Your first value is {} your second value is {}".format(amount1, amount2)

This will automatically handle the data type conversion, so there is no need for str().

Consult the Python docs for detailed information:

https://docs.python.org/3.6/library/string.html#formatstrings

Sign up to request clarification or add additional context in comments.

3 Comments

stackoverflow.com/a/53865969/3052535 is better to read and shorter.
@Manuel It requires 3.6+, and is not necessarily easier to read in complex cases. This way you can also do: "{arg1}".format(arg1=my_var) btw
Didn't know the 3.6 restriction. Cool thanks! Giving the argument name is very nice.
16

With Python 3.6+ (PEP498), you can use formatted string literals, also known as f-strings:

amount1 = input('Insert your value: ')
amount2 = input('Insert your value: ')

print(f'Your first value is {amount1}, your second value is {amount2}')

Comments

1

You could also use the old kind of % formatting:

print "this is a test %03d which goes on" % 10

This page https://pyformat.info/ has quite a nice comparison !

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.