2016-04-15 124 views
1
word1 = input("Random Name (ex. Ryan):") 
word2 = input("Your name (ex. why do you need an example of your name?):") 

print("To:", word1, "@gmail.com") 
print("From:", word2, "@outlook.com") 

現在,除了第1個字和第2個字之外,現在您幾乎需要忽略所有內容。字符串連接和格式化| Python

我只是想知道這是爲什麼輸出

To:name @gmail.com 

,而不是要:[email protected]

提前感謝你們!

回答

3

因爲在python print中自動在print語句的參數之間加上空格,即用逗號分隔的東西。如果你想刪除它,你可以將sep關鍵字設置爲空格之外的其他分隔符。將其設置爲空白字符串以便沒有分隔符。

>>> print('A','string','with','spaces.') 
A string with spaces. 
>>> print('A','string','with','no','spaces.', sep = '') 
Astringwithnospaces. 
+0

非常感謝! – ValiantChampion

+1

即使我會說其他答案是走的方式,它真的很好,以便您可以更改打印功能中的分隔符 – muthan

+0

另一個答案提供了對格式化的更多控制,但這也很有用。請注意,還有一個'end'關鍵字,用於改變字符串尾部的內容。默認情況下它是一個換行符'\ n',但是您可以將其設置爲''''以不打印到新行。 – zephyr

3

你可以做

print("To:" + word1 + "@gmail.com") 

或者

print("To:%[email protected]" % word1) 

或者

print("To:{}@gmail.com".format(word1)) 

或如評論所說:

print("To:{0:s}@gmail.com".format(word1)) 

要打印的價值你想要的方式

print(some_val, some_val2, some_val3, ...)將增加這些值之間的空間。

+1

我會使用'''print(「To:{0:s} @ gmail.com」.format(word1))'''這樣''''''對於那些沒有看到這個表示法。 '''0'''是第一個格式化的東西,'''''''表示一個字符串。 –