2017-01-23 77 views
1

我以初學者的Python當然,這是活性的教訓之一:輸出打印轉義字符[]

我的代碼:

print "How old are you?", 
age = raw_input() 
print "How tall are you?", 
height = raw_input() 
print "How much do you weigh?" 
weight = raw_input() 
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) 

我再通過PowerShell和投入運行數據時提示,但是當我在5'9" 鍵入高度和它打印出的最後一個字符串,它看起來像這樣輸入:

So, you're '24' old, '5\'9"' tall and '140 lbs' heavy. 

我怎麼反斜槓走開

回答

4

通過使用%r格式標誌,你要打印字符串的再版。這種區別在this question很好地解釋,但在你的情況具體爲:

>>> s = '5\'9"' # need to escape single quote, so it doesn't end the string 
>>> print(s) 
5'9" 
>>> print(str(s)) 
5'9" 
>>> print(repr(s)) 
'5\'9"' 

的再版,在謀求成爲明確的,已經包圍在單引號括起來,逃到每個字符串中的單引號。這與您在源代碼中輸入常量字符串的方式很相似。

爲了得到您要的結果,請在格式字符串中使用%s格式標誌而不是%r

+0

謝謝你向我解釋這個!我仍然試圖理解不同輸入格式之間的差異。 Tyty! – bootoons

+3

不用擔心!如果這個或摩西的答案回答了你的問題,不要忘記用左邊的複選標記來接受其中的一個;這將把你的問題排除在需要答案的問題隊列之外。歡迎來到StackOverflow! –

2

不要在您的格式使用再版%r,使用%s和琴絃只是插不逃避任何字符:

print "So, you're %s old, %s tall and %s heavy." % (age, height, weight) 
#    ^ ^  ^