I'm trying to write a code that will take multiple strings at specific indexes of a list, and append them to a list as follows
['Caleb', 'Smith'] ===> ['Caleb Smith']
but I can't figure out how to do that, what I keep getting is
['Caleb', 'Smith'] ===> ['CalebSmith']
code:
with open("student_data.txt", "r") as file1:
SDN = file1.readlines()
SD = []
for line in SDN:
without_newline = line[:-1]
SD.append(without_newline)
SDf = []
id = []
first = []
last = []
adress = []
for x in range (0, 10):
SDf.extend(SD[x].split(' '))
for x in range (0, 80, 8):
id.append(SDf[x])
first.append(SDf[x 1])
last.append(SDf[x 2])
adress.append(SDf[x 3] SDf[x 2])
data for student file:
125001 John Smith 12 First Road London N1
125002 Alan Smith 35 Second Avenue London N12
125003 Mary Jones 258 Nice Road London E17
125004 Elisabeth Davies 33 Third Avenue London SW19
125005 Mark Henry 45 Lovely Gardens London W8
125006 Philip May 1 Near Street London N1
125007 Jane Gill 7 Fifth Street London EC1
125008 Susan Wright 23 Nowhere Road London N10
125009 Alan Lee 345 Season Street London E1
125010 Olivia Rex 12 Beautiful Road London N12
CodePudding user response:
If you're just trying to concatenate the given strings with a space between them, then you can use the join
method on a string (the string that is the delimiter you want to go between the items).
>>> items = ['Caleb', 'Smith']
>>> " ".join(items)
'Caleb Smith'
>>> "...".join(items)
'Caleb...Smith'
Notice how the output was a string. If you need the output to be a list containing that one string, then just put the string in a list:
>>> [" ".join(items)]
['Caleb Smith']
CodePudding user response:
>>> l = ["Caleb", "Smith", "Edward"]
>>> i = 0
>>> j = 1
>>> " ".join(l[i:j 1])
'Caleb Smith'
Explanation:
" ".join()
takes a list and joins the elements with the string on which it is used.
[i:j 1]
splices the list by indexes i
and j
CodePudding user response:
Let's streamline this:
with open("student_data.txt", "r") as file1:
SDN = file1.readlines()
SD = []
for line in SDN:
without_newline = line[:-1]
SD.append(without_newline)
With:
with open("student_data.txt", "r") as file1:
SDN = file1.readlines()
SD = [line.rstrip() for line in SDN]
Now:
SDf = [record.split(' ') for record in SD]
Replaces:
for x in range(0, 10):
SDf.extend(SD[x].split(' '))
And now this:
for x in range (0, 80, 8):
id.append(SDf[x])
first.append(SDf[x 1])
last.append(SDf[x 2])
adress.append(SDf[x 3] SDf[x 2])
Can be:
for x in SDf:
id.append(x[0])
first.append(x[1])
last.append(x[2])
adress.append(' '.join(x[3:]))
This joins the 4th (Python lists are indexed starting at 0
) to the last element in each list with a space. Yielding, for instance: '12 First Road London N1'
.
Ideally, do not manage aggregate data with "parallel" data structures, but create an aggregate data structure that holds the different pieces of related data in a single object. That is beyond the scope of this question, though.