Turn a list into a string and remove [ ]


#1


https://www.codecademy.com/courses/python-beginner-en-pwmb1/1/1?curriculum_id=4f89dab3d788890003000096


Hi guys,
I'm doing a Python Lists and Dictionaries exercise and I'm encountering some prob

suitcase = ["sunglasses", "sunscreen", "toothbrush", "normal clothes"]
print suitcase

When I run the code above I'll get:

['sunglasses', 'sunscreen', 'toothbrush', 'normal clothes']

on the console, which is normal, but I don't want the [ ] to be included so I write sth like this

suitcase = ["sunglasses", "sunscreen", "toothbrush", "normal clothes"]
print str(suitcase) - str(suitcase)[0] - str(suitcase)[len(str(suitcase))]

and get the error message "TypeError: unsupported operand type(s) for -: 'str' and 'str'"

Can you explain what's wrong with the code and give me some advice, pls?
Thanks in advance!


#2

i am not even sure what you are trying to do? Why not simple use the built in join function? Which is designed to this:

print " ".join(suitcase)

?


#3

What would subtracting a string from a string do? You'll have to start by describing what it is you want to do.

The brackets aren't part of the data, so you can't remove them, there is nothing to remove. If you mean that you want to format some particular string based on your list, then take a look at string formatting.

Above all you have to start by deciding what you want to do so that you can ask/search for it.


#4

"Subtracting..." is the way that I thought would remove a string from another string

Okay, I will state my intention clearer

Thanks!


#5

Well, I stated that I want the [ ] out of the console

I am new to Python so pretty much everything is new to me, including this join function

Thanks for helping!


#6

Intention comes first. That's where you start.

You have a list, you're not happy with its default string representation.

You could use the default string representation to create another one with things removed, but it would be far easier to create a string based on the list itself.

If the only thing you want to remove is the first and last character, then you could do that very easily with slicing notation.

However, I'd still create that string from the list itself, its join method would make that trivial. You can find a description of it here: https://docs.python.org/2/library/stdtypes.html#str.join
or by doing help(str.join) or print str.join.__doc__ if codecademy's interface doesn't play nice with the help function


#7

Alright, thanks! I will look into that


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.