如果我使用变量,如何在print语句中包含引号

pk.*_*pk. 1 python printing variables

word = input("Enter a word: ")
word_length = len(word)

print("The length of", word,"is ", word_length)
Run Code Online (Sandbox Code Playgroud)

如果是'back',则输出为:

The length of back is 4
Run Code Online (Sandbox Code Playgroud)

我希望输出为:

The length of 'back' is 4
Run Code Online (Sandbox Code Playgroud)

Bha*_*Rao 5

好方法:

最好的方法是使用 format

print("The length of '{}' is {}".format(word, word_length))
Run Code Online (Sandbox Code Playgroud)

糟糕的方式:

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

print("The length of '%s' is %s" % (word, word_length))
Run Code Online (Sandbox Code Playgroud)

丑陋的方式:

一种方法是让你的字符串添加一个'和使用sep属性

print("The length of '", word,"' is ", word_length, sep = '')
Run Code Online (Sandbox Code Playgroud)