Jimmy50908
Jimmy50908

Reputation: 50

removing square brackets and apostrophes around a list

I am trying to write a program that takes a list of names and sorts it alphabetically then repeats it back.

Here is my code:

question = input('Students: ')
roll = print('Class Roll')
students = question.split()
students.sort()
v1 = 0
v2 = 1
for i in range(len(students)):
  person = students[v1:v2]
  print(person)
  v1 = v1 + 1
  v2 = v2 + 1

When I run the code and type in a list of names it repeats it back with [' '] around each name. Like this:

Students: Bob Adam Carl Fred
Class Roll
['Adam']
['Bob']
['Carl']
['Fred']

The only thing that I can't figure out how to fix is removing the [' '] around each name. When I try to use [2:-2] to remove them it just outputs [] for the number of names I typed in. Is there a way to remove them and if so how? I've tried to find an answer to this but I couldn't see one anywhere.

Upvotes: 1

Views: 1236

Answers (1)

NotAnAmbiTurner
NotAnAmbiTurner

Reputation: 2743

Because you are printing a slice of the list, not the string at each index. This gives you a list of one item, then prints that one-item list, hence the brackets and apostrophes (that is python's representation of a list):

person = students[v1:v2]

Eg:

>>> listy = ['a', 'b', 'c']
# if I take a slice that's just the middle item, I would get
>>> print(listy[1:2])
['b']
>>> print(listy[0:1])
['a']
# compare with
>>> print(listy[1])
b    
>>> print(listy[0])
a

You are also making it wayyyyy harder on yourself that it needs to be. You probably want:

for person in students:
  # person = students[v1:v2]
  print(person)
  # v1 = v1 + 1
  # v2 = v2 + 1

Upvotes: 1

Related Questions