1

I'm trying to figure out how to split data received from a socket. I have the sockets working and I can get the data correctly but I now want to split the data retrieved and obtain the last string. Here is what I'm trying(data is the data received from the socket)

split = data.split(' ')
print split
print split[-1]

But when I try it it wont work for some reason. Like lets say I have the string received as "test test1" I want to get test1.

11
  • Does split contain anything at all? Do you have binary data in data? Your example should work as long as it can be split correctly (assumes the string not to be zero etc.) Commented Feb 17, 2011 at 0:04
  • I'm sending the string "test test1". No binary or anything just that string. Commented Feb 17, 2011 at 0:06
  • When you say it "won't work": what does happen? Do you get an error? What shows up on screen? Commented Feb 17, 2011 at 0:11
  • Well I'm attempting to preform os.chdir(split[-1]) But I get the error sh: chdir/ not found Commented Feb 17, 2011 at 0:12
  • If you just do print split[-1], what does it show? Commented Feb 17, 2011 at 0:13

2 Answers 2

1

The following works for me:

>>> data = "chdir /"
>>> a = data.split(" ")
>>> a
['chdir', '/']
>>> a[-1]
'/'

This appears to be what you're looking for. The reason your code doesn't work likely lies with the exact content of data.

Note that using .split(" ") is slightly different than .split() when you have multiple spaces in the original string. See for example:

>>> "chdir /".split(" ")
['chdir', '/']
>>> "chdir  /".split(" ")
['chdir', '', '/']
>>> "chdir  /".split()
['chdir', '/']
Sign up to request clarification or add additional context in comments.

Comments

0

Just a note that it is bad practice to use the names of common library functions to name objects in your own code.

Sometimes it creates errors, but it always creates confusion.

1 Comment

The word 'variable' is ambiguous in Python. In your sentence it means: "the references to which names are binded, and that contain the adresses of the objects". But that is out of subject. BTW, even the word 'reference' is not very good because it is not the same as in C++ for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.