首页 > 解决方案 > 随机大写字符串中的字母

问题描述

我想随机大写或小写字符串中的每个字母。我是在 python 中使用字符串的新手,但我认为因为字符串是不可变的,所以我不能执行以下操作:

i =0             
for c in sentence:
    case = random.randint(0,1)
    print("case = ", case)
    if case == 0:
        print("here0")
        sentence[i] = sentence[i].lower()
    else:
        print("here1")
        sentence[i] = sentence[i].upper()
    i += 1
print ("new sentence = ", sentence)

并得到错误: TypeError: 'str' object does not support item assignment

但那我还能怎么做呢?

标签: pythonpython-3.xuppercaselowercase

解决方案


您可以使用str.join这样的生成器表达式:

from random import choice
sentence = 'Hello World'
print(''.join(choice((str.upper, str.lower))(c) for c in sentence))

样本输出:

heLlo WORLd

推荐阅读