是否有一种更有效/更智能的方法来随机化字符串中字母的大写字母?像这样:
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
答案 0 :(得分:7)
您可以使用random.choice()
,从str.upper
和str.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 :(得分: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))