By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 804 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

Convert a list "of positions" into a string

P: 3
Hello everybody,

I managed to convert a string of a given lenght consisting of 2 numbers only (0 and 1) into a list of positions of the number '1', (see example below).
Note: The string size is always going to be a multiple of 4!

Example for string lenght equals 8:
>>> string = "01010100"
>>> [i for i in range(len(string)) if string.startswith('1', i)]
[1, 3, 5]

Problem:
I would like to "back calculate" the original string "01010100" from the list of positions [1, 3, 5]

Means: convert the list [1, 3, 5] back to a string 01010100

Your help is appreciated.
Jun 6 '16 #1
Share this Question
Share on Google+
4 Replies


P: 3
P.S. I am using python 3.5
Jun 6 '16 #2

Expert 100+
P: 613
it's just a simple replace
Expand|Select|Wrap|Line Numbers
  1. b_string=["0" for ctr in range(8)]
  2. positions=[1, 3, 5]
  3. for position in positions:
  4.     b_string[position]="1"
  5. print b_string 
Jun 6 '16 #3

P: 3
The above "simple replacement does almost the right thing but
1st: it gives n results for n positions
result of above code is:
['0', '1', '0', '0', '0', '0', '0', '0']
['0', '1', '0', '1', '0', '0', '0', '0']
['0', '1', '0', '1', '0', '1', '0', '0']
and 2nd:
it prints out a list not a string!

I would need to have a single result string like this:
"01010100"
Jun 12 '16 #4

Expert 100+
P: 613
For #2, use "".join(the_list") to convert http://www.tutorialspoint.com/python/string_join.htm For #1, lists use offsets, so the first element is at zero offset (at the beginning). The second element is at offset one (skip over the first/go to the end of the first=start of second in memory), etc. So 3 would skip to the beginning of the 4th element. Adjust the numbers accordingly (num-1? don't understand exactly what you are saying). This can also be done with strings by using a for loop and adding each character to a new string unless it is at one of the replacements, and then add the "1 instead, but using a list is much more straight forward.
Jun 12 '16 #5

Post your reply

Sign in to post your reply or Sign up for a free account.