Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

larswik

macrumors 68000
Original poster
Sep 8, 2006
1,552
11
A couple of other folks (lee1210 and eddietr) have been helping me with a binary to text program. They recommended using lists and slicing them. I am trying to get the slicing of a list to read as '23' not ('2', '3') on the print statement. I looked through the book but I could not find it. I am sure I am looking in the wrong place. Here is the code so far. How can I add the string elements into 1 new string that is something like 23456 instead of ('2','3','4' and so on)?

Code:
#Slicer test

numbers = ("1","2","3","4","5")

nums = numbers[1:3]

if nums == "23":
    print "it is 23"
else:
    print "this is not 23, it is ", nums
 
You currently have a list of lists, and a slice of this is still a list of lists. Just assign "123456" to a variable, say, numlist. To get "23", you could use:
Code:
newStr=numlist[1:2]

I don't know the fast way to "collapse" a list of lists to a single list in python, but I don't think you need to right now.

-Lee

Edit: it looks like join() will collapse a sequence of strings into a single string. If you had to use a list of strings, you could use join first, then slice, or slice first then join. You could get "23 like this:
Code:
newStr=join(numbers[1:2])
 
Yeah, I would agree with Lee1210. It's easier, and makes more sense, to think in terms of Strings, rather than lists of characters.

Strings in python behave like lists of characters, but they are not the same thing. And so there is a difference between "123" and ['1','2','3']

The syntax for joining a list of characters together as a single string is actually this:

Code:
newStr = "".join(numbers[1:2])
 
Oops. Was posting from my phone, so couldn't try to run the example. As stated in the previous thread, python isn't a language I'm fluent in (I'm used to array slicing in fortran, which is one based and inclusive on both bounds, so getting the python slicing down is a challenge). I should probably leave the python stuff to the experts, as the vocab(i.e. string, list, sequence, etc.) and some of the usage I don't quite have down. One way or the other, hopefully the OP has what they need.

-Lee
 
Thanks again guys. Sorry for the late reply I was in Vegas at NAB and I am just getting back into it again.

Thanks for the info!!!!

-Lars
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.