2017-03-16 86 views
0

使用Python 2.7,假設我有兩個變量:字符串處理for循環

encoded_username = 'bender_in_soup_1234' 
code = '000204071012' 

code的字符串實際上指定大寫字符在encoded_username位置。即00意味着第一個字符是大寫。 02意味着第三個字符是大寫。 04意味着第五個字符是大寫。等等。它可能會去99usernames不超過100個字符)。

完全解碼的用戶名是:

decoded_username = 'BeNdEr_In_SoUp_1234' 

什麼是最有效的方法(在Python 2.7)使用code提供的encoded_username解碼?


我想:

upper_case_positions = [code[i:i+2] for i in range(0,len(code),2)] 
for position in upper_case_positions: 
    encoded_username[position] = encoded_username[int(position)].upper() 
return encoded_uname 

但這只是給了我'str' object does not support item assignment

此外,我將在解碼時解析多個用戶名,即上面的代碼將嵌套在for循環中。在for循環中有for循環讓我覺得可能有更高效的解決方案。你們有什麼建議?我非常感興趣。

+0

已經嵌套for循環是不是在大多數情況下,效率低下。 –

回答

2

如何如下:

encoded_username = 'bender_in_soup_1234' 
code = '000204071012' 

upper_case_positions = [int(code[i:i+2]) for i in range(0, len(code), 2)] 

decoded_username = ''.join(let.upper() if pos in upper_case_positions else let 
          for pos, let in enumerate(encoded_username)) 
print decoded_username 

首先,你需要用你的upper_case_positions爲整數,以確保它們可用作位置。我們列舉這個詞來返回每個角色及其相關位置,並根據需要更改情況。使用空字符串加入我們的輸出用戶名。這版畫,一如預期,'BeNdEr_In_SoUp_1234'

1

在這裏,你可以選擇使用ordchr的形式給出:

encoded_username = 'bender_in_soup_1234' 
code = '000204071012' 


def upperText(s, pos): 
    gap = ord("a") - ord("A") 
    upper_case_positions = [int(pos[i:i + 2]) for i in xrange(0, len(pos), 2)] 
    txt = map(ord, s) 
    for i in upper_case_positions: 
     txt[i] -= gap 
    return "".join(map(chr, txt)) 

print upperText(encoded_username, code) 
BeNdEr_In_SoUp_1234 
+0

's'是'encoded_username'字符串,是否正確? –

+0

@HassanBaig是的 – Netwave

1

字符串是不可改變的Why are Python strings immutable? Best practices for using them

您可以使用正則表達式中塊分割https://stackoverflow.com/a/25430739/123808

你可以在列表中進行變換(這是可變的),並在您完成變形後重建您的字符串

import re 

encoded_username = 'bender_in_soup_1234' 
code = '000204071012' 

encoded_username_list = list (encoded_username) 

upper_case_positions = [int(pos) for pos in re.findall('.{2}', code)] 

for position in upper_case_positions: 
    encoded_username_list[position] = encoded_username[position].upper() 

print "".join(encoded_username_list) 

BeNdEr_In_SoUp_1234

+0

有興趣知道如何使用正則表達式分割比[[int(pos [i:i + 2])xrange(0,len(pos),2)]' –

+0

更好的可讀性,但對於xrange(0,len(pos),2)]'中的i,它可能實際上比[[int(pos [i:i + 2])]慢(因爲我們需要在前一種情況下使用're' )。 –

+0

@HassanBaig它只是指出了使用正則表達式分割大小爲2的塊。我發現它更可讀但效率更低。沒有仔細閱讀你的問題,直到str錯誤讀取它不是效率的要求 – rapdum