2017-08-07 115 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,不能大写 –