2017-08-07 117 views
3

是否有更高效/更聰明的方式來隨機化字符串中的大寫字母?就像這樣:隨機化字符串的大小寫

input_string = "this is my input string" 
for i in range(10): 
    output_string = "" 
    for letter in input_string.lower(): 
     if (random.randint(0,100))%2 == 0: 
      output_string += letter 
     else: 
      output_string += letter.upper() 
    print(output_string) 

輸出:

thiS iS MY iNPUt strInG 
tHiS IS My iNPut STRInG 
THiS IS mY Input sTRINg 
This IS my INput STRING 
ThIS is my INpUt strIng 
tHIs is My INpuT STRInG 
tHIs IS MY inPUt striNg 
THis is my inPUT sTRiNg 
thiS IS mY iNPUT strIng 
THiS is MY inpUT sTRing 
+2

'''.join(c.upper()if random()> 0.5 else c for input_string)' – Maroun

+1

@MarounMaroun我在四種方式(包括我的)使用'timeit',你的方式似乎大幅度擊敗了每個人。 (無法獲得'map'的方式來工作) –

+1

對於一個公平的測試,你應該做'''.join(c.upper()if random()> 0.5 else c for input_string.lower()) ',但是檢查實現實際上我並不感到意外'random.choice()'比較慢(但更易讀)。你也可以嘗試'''.join(ls [random.getrandbits(1)](c)for c in s)'。另外,它應該是'> ='? @MarounMaroun相關問題:https://stackoverflow.com/questions/6824681/get-a-random-boolean-in-python –

回答

7

你可以使用random.choice(),從str.upperstr.lower採摘:

>>> from random import choice 

>>> s = "this is my input string" 
>>> lst = [str.upper, str.lower] 

>>> ''.join(choice(lst)(c) for c in s) 
'thiS IS MY iNpuT strIng' 

>>> [''.join(choice(lst)(c) for c in s) for i in range(3)] 
['thiS IS my INput stRInG', 'tHiS is MY iNPuT sTRinG', 'thiS IS my InpUT sTRiNg'] 
1

你可以使用地圖和用字符串應用隨機因素這樣做:

import random 

StringToRandomize = "Test String" 

def randomupperfactor(c): 
    if random.random() > 0.5: 
     return c.upper() 
    else: 
     return c.lower() 

StringToRandomize =''.join(map(randomupperfactor, StringToRandomize)) 
+1

爲什麼downvote? – Maroun

+1

@MarounMaroun我沒有downvote,方法沒問題,但我認爲'else'子句丟失。變量名稱也應符合PEP8,不能大寫 –