python - 如何在字符串中随机大写字符?

标签 python string random

我想要一种获取字符串变量并随机化哪些字母为大写的方法,如下所示:

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/

相关文章:

python - 在 Windows 上安装 TensorFlow (Python 3.6.x)

python - "grep"大文件的最快方法

python - 如何通过在 Python 3 中作为命令行参数提供的转义序列拆分 UTF-8 字符串?

javascript - 如何返回数组中最长的字符串 - 即使数组包含不是字符串的项目?

arrays - 使用数组生成随机函数,不重复 swift

Python Flask + AngularJS + DevExtreme

Javascript正则表达式查找字符串并从整个字符串中提取它

random - 如何生成随机时间?

random - rand() 函数有多随机?

python - 如何比较两个 ctypes 对象是否相等?