是否有更高效/更聪明的方式来随机化字符串中的大写字母?就像这样:随机化字符串的大小写
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
'''.join(c.upper()if random()> 0.5 else c for input_string)' – Maroun
@MarounMaroun我在四种方式(包括我的)使用'timeit',你的方式似乎大幅度击败了每个人。 (无法获得'map'的方式来工作) –
对于一个公平的测试,你应该做'''.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 –