我有一个像'0111111011111100'
这样的字符串,我希望将每四个字符分开,这样就可以了:
0111,1110,1100
然后我想用其他值替换那些。
到目前为止,这是我的代码,但它无法正常运行:
答案 0 :(得分:4)
您可以list-comprehension
使用string
indexing
:
s = "0111111011111100"
[s[i:i+4] for i in range(0,len(s),4)]
给出:
['0111', '1110', '1111', '1100']
然后为每个dictionary
要翻译的内容定义nibble
:
d = {'0111': 'a', '1110': 'b', '1111': 'c', '1100': 'd'}
然后你可以将翻译推到list-comp
:
[d[s[i:i+4]] for i in range(0,len(s),4)]
会给出:
['a', 'b', 'c', 'd']
并最终使用str.join
将其重新放回string
,使整个转换成为一行:
''.join(d[s[i:i+4]] for i in range(0,len(s),4))
给出:
'abcd'
事实上,这里使用generator
表达式,因为它们比list-comprehensions
答案 1 :(得分:0)
如果您想用字符串替换字符串中的每个四位数组,可以使用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'
答案 2 :(得分: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)
答案 3 :(得分:0)
这可能对您有所帮助:
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)