如何打印dict字符串



我正试图从带括号的原始输入中打印字符串。

这是我的密码。

words = (raw_input('Please enter a string:  '))
names = list(words)
print names

我得到这个:

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

我只需要这样:

[Hello]

您不需要list,只需使用format%s:

words = raw_input('Please enter a string: ')
names = '[{}]'.format(words) # or '[%s]'%words
print names

如果用户写了多个单词,你可以先将输入分开并打印出来(注意,你需要确保它们之间有空格):

print words.split()

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()在每个空间分割字符串以形成字符串列表。

编辑:我只是知道你想要在括号之间打印字符串,没有引号,Kasra的格式字符串很好。

尝试使用:

words=(raw_input('请输入字符串:'))

names=[]

names.append(words)

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

最新更新