2

I have a string such as '0111111011111100' and I want to separate every four characters so here that would be:

0111,1110,1100

Then I want to replace those with another values.

Here is my code so far, but it doesn't work properly:

5

4 Answers 4

4

You can use a list-comprehension with string indexing:

s = "0111111011111100"
[s[i:i+4] for i in range(0,len(s),4)]

gives:

['0111', '1110', '1111', '1100']

and then define a dictionary for what you want each nibble to translate to:

d = {'0111': 'a', '1110': 'b', '1111': 'c', '1100': 'd'}

and then you can shove the translating into the list-comp:

[d[s[i:i+4]] for i in range(0,len(s),4)]

which would give:

['a', 'b', 'c', 'd']

and finally use str.join to put this back into a string, making the entire conversion one-line:

''.join(d[s[i:i+4]] for i in range(0,len(s),4))

which gives:

'abcd'

as a matter of fact, a generator expression is being used here as they are more efficient than list-comprehensions

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to replace each group of four digits in string with some value you could use dict

line='0111111011111100'
lookup = {'0111': 'a', '1110': 'b', '1100': 'c'} # add all combination here
"".join(lookup.get(line[i:i+4], 'D') for i in range(0, len(line), 4)) # 'D' is default value
Out[18]: 'abDc'

Comments

0

Here's something that might help you:

str = "0111111011111100"

n = 4

# Create a list from you string with 4 characters in one element of list.
tmp_list = [str[i:i + n] for i in range(0, len(str), n)]
# tmp_list : ['0111', '1110', '1111', '1100']

for n, i in enumerate(tmp_list):
    if tmp_list[n] == "0111":
        tmp_list[n] = "A"
    # elif ....
    # Todo:
    # Populate your if-elif requirements here.   

result_str = ''.join(tmp_list)

Comments

0
line='0111111011111100'
# define a dictionary with nibbles as values
dict = { '0111': 'a', '1110': 'b', '1111': 'c', '1100': 'd'}

# define chunk size
n = 4

# use a list comprehension to split the original string into chunks
key_list = [line[i:i+n] for i in range(0, len(line), n)]

# use a generator expression to replace keys in the list with
# their dictionary values and join together
key_list = ' '.join(str(dict.get(value, value)) for value in key_list)
print(key_list)

2 Comments

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
added some explanatory notes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.