[英]how to split a string in python
我有一个字符串,例如'0111111011111100'
,我想每四个字符分开,因此在这里是:
0111,1110,1100
然后,我想用另一个值替换那些值。
到目前为止,这是我的代码,但是无法正常工作:
您可以将list-comprehension
与string
indexing
:
s = "0111111011111100"
[s[i:i+4] for i in range(0,len(s),4)]
得到:
['0111', '1110', '1111', '1100']
然后为每个nibble
要翻译的内容定义一个dictionary
:
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
更有效
如果要用某个值替换字符串中的每组四个数字,则可以使用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)
以下内容可能会对您有所帮助:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.