tags:

views:

112

answers:

8
+1  Q: 

Question for join

Hello Folks,

I have no clue about python and started to use it on some files. I managed to find out how to do all the things that I need except for 2 things. Ipadd = string.join (line['0,1,2,4,5,6']) does not work if I make it (line[0:2]) It prints out the first two fields and thats good so far but I need field 4 and 6 also. but (line[0:2:4:6]) is not working and different other things that I tryed. How can I accomplish this? similar to awk '{ print $1 $2 $5 $7 }'

2nd how can I delete the last character of the line. There is an additional ' that I don't need.

+2  A: 

You don't want to use join for that. If you just want to print some bits of a list, then specify the ones you want directly:

print '%s %s %s %s' % (line[0], line[1], line[4], line[6])
Dominic Rodger
Shouldn't the second item in the tuple be `line[1]` instead? (Assuming he wants the 2nd element in the list)
Manoj Govindan
@Manoj, thanks - edit made.
Dominic Rodger
Hi Thanks, that helps so far! but I did a split before and thought to use a join after that.Thank you for the quick answer!
tiger
@tiger - You could use `join`, but I reckon that makes your code more complicated not less.
Dominic Rodger
`%` is on the track to deprecation and shouldn't be used.
Jesse Dhillon
Yes thank you for the hint.The line has several cells or fields and if I like to print out only some of them I thought I need to split them.I seemd logic to me to join them after that :-)Script has 19 codelines now so it is not realy complicated I think!I just need to add someting to write the outcome in a file and than I'm done.But it is the first thing in python so I'm happy that it works!
tiger
A: 

Answer to the second question:

If your string is contained in myLine, just do:

myLline = myLine[:-1]

to remove the last character.

Or you could also use rstrip():

myLine = myLine.rstrip("'")
Felix Kling
Thank you [:-1] steals the las cell, I had that before.I have like 10 to 13 cells at the end so if I have 10 cells the -1 prints out nothing.Location = Location.rstrip("'") did it!
tiger
+1  A: 
l = []
l.extend(line[0:2])
l.append(line[5]) # fourth field
l.append(line[7]) # sixth field
string.join(l)

Alternatively

"{l[0]} {l[1]} {l[4]} {l[5]}".format(l=line)

Please see PEP 3101 and stop using the % operator for string formatting.

Jesse Dhillon
Thanks for pointing to the PEP.
xtofl
Thanks @xtofl, I was just following the OP's example.
Jesse Dhillon
+2  A: 

Assuming that the line variable should contain a line of cells, separated by commas...

You can use map for that:

line = "1,2,3,4,5,6"
cells = line.split(",")
indices=[0,1,4,6]
selected_elements = map( lambda i: cells[i], indices )
print ",".join(selected_elements)

The map function will do the on-the-fly function for each of the indices in the list argument. (Reorder to your liking)

xtofl
+1  A: 
>>> token = ':'
>>> s = '1:2:3:4:5:6:7:8:9:10'
>>> sp = s.split(token)
>>> token.join(filter(bool, map(lambda i: i in [0,2,4,6] and sp[i] or False, range(len(sp)))))
'1:3:5:7'
Daniel Kluev
A: 

Hi, question is answered!

Thanks for your quick help, it took me hours to search and figure the script out myself. But you helped me to finish it in minutes :-)

Thank you so much it worked now.

tiger

tiger
@tiger: You should put that in comments attached to some answer (or even question), you should not create an answer to put it... (now you can still delete it).
kriss
how can I delete it?
tiger
@tiger: at the bottom of the answer you see some links link|delete|edit|flag (the exact list depends of your points, I don't remember exact rights for new users with one point, probably at least edit and delete for your own answers). Just click on 'delete' and this answer will disappear for others (you'll still see it as 'deleted' with red new link 'undelete').
kriss
This is not an **answer**. It's just a comment. Please delete non-answers.
S.Lott
And please select the best, most helpful answer as solution by clicking green tick.
Tony Veijalainen
Jesse Dhillon
+2  A: 

You could use the following using list comprehension :

indices = [0,1,4,6]
Ipadd = string.join([line[i] for i in xrange(len(line)) if i in indices])

Note : You could also use :

Ipadd = string.join([line[i] for i in indices])

but you will need a sorted list of indices without repetition of course.

Elenaher
@Elenaher: or sort and duplicate removal can be done by python `[line[i] for i in sorted(set(indices))]`
kriss
@kriss Indeed, it's maybe the best solution.
Elenaher
+5  A: 

Provided the join here is just to have a nice string to print or store as result (with a coma as separator, in the OP example it would have been whatever was in string).

line = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

print ','.join (line[0:2])

A,B

print ','.join (line[i] for i in [0,1,2,4,5,6])

A,B,C,E,F,G

What you are doing in both cases is extracting a sublist from the initial list. The first one use a slice, the second one use a list comprehension. As others said you could also have accessed to elements one by one, the above syntaxes are merely shorthands for:

print ','.join ([line[0], line[1]])

A,B

print ','.join ([line[0], line[1], line[2], line[4], line[5], line[6]])

A,B,C,E,F,G

I believe some short tutorial on list slices could be helpfull:

  • l[x:y] is a 'slice' of list l. It will get all elements between position x (included) and position y (excluded). Positions starts at 0. If y is out of list or missing, it will include all list until the end. If you use negative numbers you count from the end of the list. You can also use a third parameter like in l[x:y:step] if you want to 'jump over' some items (not take them in the slice) with a regular interval.

Some examples:

l = range(1, 100) # create a list of 99 integers from 1 to 99
l[:]    # resulting slice is a copy of the list
l[0:]   # another way to get a copy of the list
l[0:99] # as we know the number of items, we could also do that
l[0:0]  # a new empty list (remember y is excluded]
l[0:1]  # a new list that contains only the first item of the old list
l[0:2]  # a new list that contains only the first two items of the old list
l[0:-1] # a new list that contains all the items of the old list, except the last
l[0:len(l)-1] # same as above but less clear 
l[0:-2] # a new list that contains all the items of the old list, except the last two
l[0:len(l)-2] # same as above but less clear
l[1:-1] # a new list with first and last item of the original list removed
l[-2:] # a list that contains the last two items of the original list
l[0::2] # odd numbers
l[1::2] # even numbers
l[2::3] # multiples of 3

If rules to get items are more complex, you'll use a list comprehension instead of a slice, but it's another subjet. That's what I use in my second join example.

kriss
this does not work.it says: print ' '.join (line[0], line[1], line[4], line[6])TypeError: join() takes exactly one argument (4 given)
tiger
@tiger: oups, forgot square brackets around list. Thanks for spoting the problem. It's corrected.
kriss
yes :-) it works also!now I have the %s also kicked out, like mentioned before.
tiger
+1 for the list comprehension - much more elegant than my `map` solution!
xtofl
@tiger, This answer is very thorough and if you like it you should select it.
Jesse Dhillon