Skip to main content
 首页 » 编程设计

python之如果我使用变量,如何在打印语句中包含引号

2025年05月04日52sharpest

word = input("Enter a word: ") 
word_length = len(word) 
 
print("The length of", word,"is ", word_length) 

如果单词是'back',输出将是:

The length of back is 4 

我希望输出为:

The length of 'back' is 4 

请您参考如下方法:

好的方法:

最好的方法是使用format

print("The length of '{}' is {}".format(word, word_length)) 

坏方法:

使用类似 C 的语句,请注意,这已不再强调,(但尚未正式弃用)

print("The length of '%s' is %s" % (word, word_length)) 

丑陋的方式:

一种方法是让您的字符串添加 ' 并使用 sep attribute

print("The length of '", word,"' is ", word_length, sep = '')