Convert a list "of positions" into a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DRKT
    New Member
    • Jun 2016
    • 3

    Convert a list "of positions" into a string

    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(strin g)) if string.startswi th('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.
  • DRKT
    New Member
    • Jun 2016
    • 3

    #2
    P.S. I am using python 3.5

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      it's just a simple replace
      Code:
      b_string=["0" for ctr in range(8)]
      positions=[1, 3, 5]
      for position in positions:
          b_string[position]="1"
      print b_string

      Comment

      • DRKT
        New Member
        • Jun 2016
        • 3

        #4
        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"

        Comment

        • dwblas
          Recognized Expert Contributor
          • May 2008
          • 626

          #5
          For #2, use "".join(the_lis t") 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.

          Comment

          Working...