= """
player_str id, name, dob
8, iniesta , 1984
10, messi , 1987
16 ,pedri, 2003
"""
player_str
'\nid, name, dob\n8, iniesta , 1984 \n 10, messi , 1987 \n 16 ,pedri, 2003\n '
split()
and strip()
Tony Phung
January 14, 2025
String
split()
each players by rowlist
is returned with each item or element as its own stringstrip()
white spaces before splittingRemove white space at the begininer and end of a string
iterate
through playersEach line is a single long string for each player or one column.
for i,player_line in enumerate(player_list): # iterate through each item of list and do something
print(i, repr(player_line), type(player_line)) # showing that they're indeed strings
0 'id, name, dob' <class 'str'>
1 '8, iniesta , 1984 ' <class 'str'>
2 ' 10, messi , 1987 ' <class 'str'>
3 ' 16 ,pedri, 2003' <class 'str'>
Split
player info for each playerSplit each player string into separate items, so theres 3 columns, one for each players information.
for i,player_line in enumerate(player_list): # recall can split string into a list delimited
player_item = player_line.split(",") # str: 'some,cool,string' -> list: ['some','cool','string']
print(player_item)
['id', ' name', ' dob']
['8', ' iniesta ', ' 1984 ']
[' 10', ' messi ', ' 1987 ']
[' 16 ', 'pedri', ' 2003']
repr
shows each strings valuesNotice there are unnecessary white space to be removed
for i,player_line in enumerate(player_list): # recall can split string into a list delimited
player_item = player_line.split(",") # str: 'some,cool,string' -> list: ['some','cool','string']
[print(repr(player_info)) for player_info in player_item] # need to clean each player_info
'id'
' name'
' dob'
'8'
' iniesta '
' 1984 '
' 10'
' messi '
' 1987 '
' 16 '
'pedri'
' 2003'
strip
each players informationAppend
each player to to create a players clean list
players = []
for player_line in player_list:
# each_str_list = line.split(",")
# [print(strg.strip()) for strg in each_str_list] # strip() all the white spaces away
player = [strg.strip() for strg in player_line.split(",")] # strip() all the white spaces away
print(player)
players.append(player)
['id', 'name', 'dob']
['8', 'iniesta', '1984']
['10', 'messi', '1987']
['16', 'pedri', '2003']