2014-10-16 122 views
1

我想從括號中的原始輸入打印我的字符串。如何打印字典字符串

這是我的代碼。

words = (raw_input('Please enter a string: ')) 

names = list(words) 
print names 

我得到這樣的:

['H', 'e', 'l', 'l', 'o'] 

我只需要像這樣:

[Hello] 
+0

如果用戶輸入多個單詞,預期的輸出是多少?例如,「你好,你好嗎?」? – Kevin 2014-10-16 13:52:33

+0

一切都需要放在括號中。 – pirulo 2014-10-16 13:57:34

回答

5

你不需要list,只需使用format%s

words = raw_input('Please enter a string: ') 

names = '[{}]'.format(words) # or '[%s]'%words 
print names 

如果用戶寫多了一個字,你可以先拆分輸入並打印(需要注意的是,你需要確保它們之間有空格):

print words.split() 
+0

這是我正在尋找的.. – pirulo 2014-10-16 14:07:54

+0

@pirulo歡迎您! – Kasramvd 2014-10-16 14:08:57

+0

非常感謝! – pirulo 2014-10-16 14:38:59

0
>>> words = [] 
>>> words.append(raw_input('enter the code: ')) 
enter the code: vis 
>>> words 
['vis'] 
+0

你會如何去除痣。 – pirulo 2014-10-16 14:00:29

1

嘗試使用:

詞語=(的raw_input( '請輸入字符串:'))

名稱= []

names.append(字)

2

words是一個字符串,可以視爲一個字符列表。 list(words)將字符串更改爲其字符列表。

如果你想要的是隻有一個元素(字符串)列表,請與該元素的列表:

>>> words = "This is a Test." 
>>> names = [words] 
>>> print names 
['This is a Test.'] 

如果你想要的是字符串中每個單詞的列表,拆分字符串:

>>> words = "This is a Test." 
>>> names = words.split() 
>>> print names 
['This', 'is', 'a', 'Test.'] 

.split()在每個空格處拆分字符串以生成字符串列表。

編輯:我只是明白你想要的括號內沒有引號打印的字符串,卡斯拉的格式字符串是好的。