2

Right now, here is my code:

name = raw_input("Please enter your name: ")
nameList = list(name)
del nameList[1]
newName = str(nameList)
print"Your new name is: " + str(newName) + "."

When I use this code, the problem is that the last line prints the newName like a list, even though I have converted it to a string.

Your new name is: ['j', 'k', 'e'].

I want this new name to be displayed like normal text. What am I doing wrong?

Thanks.

4

3 回答 3

5

I think you want to concatenate the elements of the list using the join string method:

>>> new_name = ['j', 'k', 'e']
>>> print ''.join(new_name)
jke

Alternatively, just don't convert the string to a list at all and use string operations to achieve what you want:

>>> name = 'jake'
>>> new_name = name[:1] + name[2:]
>>> print new_name
jke
于 2012-08-14T01:01:45.567 回答
2

我把代码弄乱了一点。尝试这个:

name = raw_input("Please enter your name: ")
nameList = list(name)
del nameList[1]
test = ''.join(nameList)
print"Your new name is: " + test + "."

希望能帮助到你。(:

于 2012-08-14T01:32:01.860 回答
1
>>> import string
>>> v = string.ascii_uppercase[:20]
>>> v
 'ABCDEFGHIJKLMNOPQRST'
>>> v = list(v)
>>> v[:10]
  ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

>>> v1 = ''.join(v)
>>> v1
  'ABCDEFGHIJKLMNOPQRST'

Alternatively, i believe you can do what you want in a single line of code (once you have retrieved the user input and bound it to a variable) so after your first line:

print("name is {0}{1}".format(name[:1], name[2:]))
于 2012-08-14T01:04:51.713 回答