2014-10-16 124 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()在每个空格处拆分字符串以生成字符串列表。

编辑:我只是明白你想要的括号内没有引号打印的字符串,卡斯拉的格式字符串是好的。