-1

I currently have a list with a bunch of binary values which are in string format. I would like to add a space in between every 4th value so a binary value such as:

'111111111111'

becomes

'1111 1111 1111'

For example purposes, lets say my current list is:

bin = ['0001', '1111', '111111111111']

and I want a new list with the values:

new_bin = ['0001', '1111', '1111 1111 1111']

How do I iterate over the list and add the necessary white spaces in between every 4th character? The strings which only have 4 characters do not apply and do not need to be adjusted.

Bipon Roy
  • 53
  • 5

2 Answers2

2

You can iterate over a list or a string in Python using a for loop.
https://docs.python.org/3/tutorial/controlflow.html#for-statements

Then you can just append each character in each string to a list, and at every 4th character you append whitespace. Finally, you join the list by using the string object's join method on the list. https://docs.python.org/2/library/stdtypes.html#str.join

Kevin Welch
  • 1,488
  • 1
  • 9
  • 18
2

this works for me, assuming we have to count from the left: '1111 11', not '11 1111' in case of 6 digits:

>>> def add_spaces(a) :
...     result = ''
...     for i in range(0,len(a),4) :
...         if i > 0 :
...             result += ' '
...         result += a[i:i+4]
...     return result
... 
>>> add_spaces('1111')
'1111'
>>> add_spaces('11111')
'1111 1'
>>> add_spaces('111111')
'1111 11'

testing with your data:

>>> bin = ['0001', '1111', '111111111111']
>>> [add_spaces(i) for i in bin]
['0001', '1111', '1111 1111 1111']
>>> 
lenik
  • 23,228
  • 4
  • 34
  • 43