How to insert a variable value in a string in python

前端 未结 3 1494
不思量自难忘°
不思量自难忘° 2021-01-18 11:57

Here is a simple example

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


        
相关标签:
3条回答
  • 2021-01-18 12:31

    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 !

    0 讨论(0)
  • 2021-01-18 12:37

    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}')
    
    0 讨论(0)
  • 2021-01-18 12:49

    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

    0 讨论(0)
提交回复
热议问题