簡體   English   中英

如何在python中分割字符串

[英]how to split a string in python

我有一個字符串,例如'0111111011111100' ,我想每四個字符分開,因此在這里是:

0111,1110,1100

然后,我想用另一個值替換那些值。

到目前為止,這是我的代碼,但是無法正常工作:

您可以將list-comprehensionstring 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM