我想要一种获取字符串变量并随机化哪些字母为大写的方法,如下所示:
upperRandomizer("HelloWorld") == "HeLLoWORlD"
到目前为止我已经试过了:
for p in strVar:
result = ""
if random.choice((True, False)):
result += p.upper()
else:
result += p
但是代码只吐出字符串变量的最后一个字母。我尝试使用 join() 方法但没有成功。任何帮助将不胜感激。
最佳答案
将您的 result
变量移到循环之外。现在,每次循环遍历列表中的字符时都会重新创建它。
result = ""
for p in strVar:
if random.choice((True, False)):
result += p.upper()
else:
result += p
关于python - 如何在字符串中随机大写字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65689286/