如果使用variab,如何在print语句中包含引号

2024-05-07 23:49:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

print("The length of", word,"is ", word_length)

如果word是'back',那么输出将是:

The length of back is 4

我希望输出为:

The length of 'back' is 4

Tags: oftheinputlenisbacklengthword
2条回答

您可以使用单词的repr来包含Python引号(例如,它们出现在交互式解释器中);这有一个额外的好处,即当引号已经在字符串中时,可以合理地工作:

print("The length of", repr(word), "is", word_length)

好办法是:

最好的方法是使用^{}

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

坏方法:

使用C-like语句时,请注意这一点没有被强调(但还没有正式地弃用

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

丑陋的方式:

一种方法是使用'^{} attribute将字符串相加

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

相关问题 更多 >