How to insert a variable value in a string in pyth

2019-02-24 05:37发布

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?

3条回答
forever°为你锁心
2楼-- · 2019-02-24 06:02

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}')
查看更多
SAY GOODBYE
3楼-- · 2019-02-24 06:12

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 !

查看更多
劫难
4楼-- · 2019-02-24 06:20

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

查看更多
登录 后发表回答