gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
python拼接字符串变量
- User
python拼接字符串变量
- Assistant
可以使用加号“+”来将多个字符串变量拼接在一起,例如:
codename = "Tom" age = 20 sentence = "My name is " + name + " , and I am " + str(age) + " years old." print(sentence)输出:
codeMy name is Tom , and I am 20 years old.另外,也可以使用format方法来格式化字符串,例如:
codename = "Tom" age = 20 sentence = "My name is {} , and I am {} years old.".format(name, age) print(sentence)输出:
codeMy name is Tom , and I am 20 years old.在format方法中,可以使用{}来代表需要替换的位置,然后使用format方法的参数按顺序对应填充这些位置。如果需要填充的是一个变量,只需要在{}中使用变量的名字即可。