Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python to break a continuous string into components?

Tags:

python

This is similar to what I want to do: breaking a 32-bit number into individual fields

This is my typical "string" 00000000110000000000011000000000

I need to break it up into four equal parts:

00000000

11000000

00000110

00000000

I need to append the list to a new text file with the original string as a header.

I know how to split the string if there were separators such as spaces but my string is continuous.

These could be thought of as 32bit and 8bit binary numbers but they are just text in a text file (for now)!

I am brand new to programing in Python so please, I need patient details, no generalizations.

Do not assume I know anything.

Thank you,

Ralph

like image 376
user925567 Avatar asked Sep 02 '11 16:09

user925567


People also ask

How do you split a string into multiple variables in Python?

Unpack the values to split a string into multiple variables, e.g. a, b = my_str. split(' ') . The str. split() method will split the string into a list of strings, which can be assigned to variables in a single declaration.

How do I split a string into different parts?

You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.


1 Answers

This should do what you want. See comprehensions for more details.

>>> s = "00000000110000000000011000000000"
>>> [s[i:i+8] for i in xrange(0, len(s), 8)]
['00000000', '11000000', '00000110', '00000000']
like image 189
robert Avatar answered Sep 28 '22 08:09

robert