I'm reading files from a text file called WeaponShack.list
These are the contents of 'weapon shack.list':
Grenade
Ak-47
Shotgun
Makarov
Minigun
Bat
Katana
Chainsaw
Flamethrower
There are no whitespaces. These items are copy-pasted as is.
I try to strip down some newline characters but the "\n" character just keeps showing up at some elements when I print the list. I don't understand why.
I tried using .strip('\n') but the "\n" characters still pop up at the end of some elements.
print("Taking weapons from Weapon shack")
weapons = []
with open("WeaponShack.list",'r') as ws:
weapons = ws.readlines()
for weapon in weapons:
weapons.remove(weapon)
weapon = weapon.strip('\n')
weapons.append(weapon)
ws.close()
print(weapons)
The expected output is:
Taking weapons from Weapon shack ['Ak-47', 'Makarov', 'Bat', 'Chainsaw', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']
But the actual output is:
Taking weapons from Weapon shack ['Ak-47\n', 'Makarov\n', 'Bat\n', 'Chainsaw\n', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']
Does anyone know why this is happening?
EDIT
My focus is why the "\n" character appears. Not how to traverse lists.
Also trying the suggestion: adding a new list
:
print("Taking weapons from Weapon shack")
weapons = []
newWeaponList = []
with open("WeaponShack.list",'r') as ws:
weapons = ws.readlines()
for weapon in weapons:
weapons.remove(weapon)
weapon = weapon.strip('\n')
newWeaponList.append(weapon)
ws.close()
print(newWeaponList)
produces this output:
Taking weapons from Weapon shack ['Grenade', 'Shotgun', 'Minigun', 'Katana', 'Flamethrower']
Weird because it doesn't show all the elements.