-3

Now I learn about network programming. I wanted to write myself a recvall function. My messages are sent through a TCP sockets and always end with the \r\n. Googling some articles and blog posts, I found a method I do not understand. Can it be written simpler?

def recvuntil(s, needle):
    data = ""
    while data[-len(needle):] != needle:
        data += s.recv(1)
    return data

The line I do not understand: while data[-len(needle):] != needle:. It does not make any sense to me (but, however, it works). -len(needle) should return a negative number and strings are numbered starting from 0 ...

mirx
  • 606
  • 1
  • 9
  • 21
  • 1
    In short `data[-len(needle):]` all the entries from len(needle) from the right to the end. In a list minus numbers cound from the end, positives from the start – Keef Baker Apr 07 '17 at 12:14
  • In other words, while the end of data doesn't match needle ... – Bull Apr 07 '17 at 12:15

4 Answers4

2

The expression data[n:] evaluates as all the elements of data from the one numbered n through to the end of the sequence. When n is negative it specifies a position starting form the right-hand end of the sequence, and so data[-n:] can be rephrased as "the last n elements of the sequence."

Since in this case the sequence is a string and n is the length of some target string, you could read the loop as "while the end of the data string isn't the target string."

It clearly wasn't written by an experienced Python programmer, however, since the colloquial spelling for this would be

while not data.endswith(target):
holdenweb
  • 33,305
  • 7
  • 57
  • 77
1

In python, you can use negative index to acess element starting from the end of the list.
Index -1 acess the last element of the list.

>>> t = [0, 1, 2, 3, 4, 5]
>>> t[-1]
5
>>> t[-1:]
[5]
>>> t[-len(t)]
0
>>> t[0] == t[-len(t)]
True
NiziL
  • 5,068
  • 23
  • 33
1

The line you are seeing is an example of both accessing an array from the back (the negative array index) and splicing.

-len(needle) will give a negative value of magnitude length of the needle list. data[-len(needle)] will get the len(needle)th value from the end of the array. The splice operator : will cause data[-len(needle):] to get all values from the len(needle)th value from the end of the array up to the end of the array.

For example, lets say len(needle) = 2 and data = [2, 5, 6, 7].

The statement data[-len(needle):] is functionally equivalent to data[-2:], which will give you [6, 7].

Ziyad Edher
  • 2,150
  • 18
  • 31
1

Say you have a list:

l = [1, 2, 4]

l[-2:] means slicing the list starting its second last element.

In [47]: l[-2:]
Out[47]: [2, 4]

So you are basically creating a new list, which is usually shorter (but can be same length as the original) which starts from an element of the original list and ends at a particular element of the original list.

elena
  • 3,740
  • 5
  • 27
  • 38