Search code examples
pythonpython-idle

Converting from list to string Python


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.


Solution

  • 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