简体   繁体   中英

how to split a string in python

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:

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

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'
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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM