Reputation: 59
I have a list in my program called student.
I append to this list a string with the name "Reece".
When I print the variable holding my name it outputs:
Reece
When I print the list which I appended the variable too it outputted:
['Reece']
How can I like strip it to remove these unwanted characters []'
The code I use is this:
name = "Reece"
print name #Outputs - Reece
student = []
student.append(name)
print student #Outputs - ["Reece"]
If I then appended another thing:
Class = "Class A"
student.append(Class)
print student #Outputs - ["Reece", "Class A"]
Upvotes: 1
Views: 2158
Reputation: 1812
It depends on the format in which you would like the list to be printed.
If you want to print the list separated by spaces, you should convert it to a string, because Python's style of printing lists is with the brackets.
print ' '.join(list)
The ' '
can be replaced with different strings that will join the strings from your list.
If you would like to print a specified element on the list on the other hand, you should use:
print list[0]
where in place of 0 you can put any number that is in the length range of the list (which means 0 to list length minus 1 as the lists are 0-based).
Finally, to print all the elements from the list, simply use:
for element in list:
print element
Upvotes: 0
Reputation: 2818
['Reece']
is the string representation of a list, the square brackets tell you that's what it is, and the quotes mark the start and end of the string in it. A longer list might look like this: ['Reece', 'Andy', 'Geoff']
.
If you'd like to display just one entry, you can refer to its place in the list, counting from zero upwards:
print student[0]
You might use the list as part of a loop:
for person in student:
print person,
The trailing comma removes new lines. If you want each name on a line by itself you can just do print person
.
It's also possible to make a single string from a list. You can do this with a string and the join
method.
" ".join(student) # will join all the list entries together with spaces in between
",".join(student) # will join all the list entries with a comma in between
" hedgehog ".join(student) # will join all the list entries with ' hedgehog ' in between
Upvotes: 0
Reputation: 32244
This should produce your desired output
print student[0]
The [ ] are printed because student is a list and [ ] is the list representation.
If you want to print multiple names in a list, you should look at the join method.
It works like this:
", ".join(["Reece", "Higgs"])
Gives:
Reece, Higgs
Upvotes: 1