number1 = int(input("请输入第一个数:")) number2 = int(input("请输入第二个数:")) # 方法一:字符串拼接,注意数字需要str()转化为字符串再拼接 print(str(number1) + " + " + str(number2) + " = " + str(number1 + number2)) # 方法二:f"{变量}" print(f"{number1} + {number2} = {number1 + number2}") # 方法三:"%d" %变量 print("%d + %d = %d" % (number1, number2, number1 + number2)) # 方法四:"{编号}".format(变量) print("{0} + {1} = {2}".format(number1, number2, number1 + number2)) # or print("{number1} + {number2} = {number3}".format(number1=number1, number2=number2, number3=number1 + number2)) # or print("{} + {} = {}".format(number1, number2, number1 + number2)) # 方法五:逗号和sep print('2019', '12', '12', sep='-')
控制台结果: 请输入第一个数:20 请输入第二个数:30 20 + 30 = 50 20 + 30 = 50 20 + 30 = 50 20 + 30 = 50 20 + 30 = 50 2019-12-12
print(f””):
格式化 {} 内容,不在 {} 内的照常展示输出,如果你想输出 {},那就用双层 {{}} 将想输出的内容包起来。
例子:
list_ = [1,2,3] print(list_, f'has a length of {len(list_)}.') # [1,2,3] has a length of 3. print(list_, f'has a length of {{len(list_)}}.') # [1,2,3] has a length of {len(list_)}. print(list_, f'has a length of {{{len(list_)}}}.') # [1,2,3] has a length of {3}.
参考链接:python字符串前加 f 的含义_(f”)在python中什么意思-CSDN博客
python五种print方法:字符串拼接,f“{变量}“,“%d“ %变量,“{编号}“.format(变量)_python print拼接字符串-CSDN博客