随机大写字符串中的字母 [英] Randomly capitalize letters in string

查看:28
本文介绍了随机大写字符串中的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to randomly capitalize or lowercase each letter in a string. I'm new to working with strings in python, but I think because strings are immutable that I can't do the following:

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

And get the error: TypeError: 'str' object does not support item assignment

但是我还能怎么做呢?

推荐答案

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

You can use str.join with a generator expression like this:

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

示例输出:

heLlo WORLd

这篇关于随机大写字符串中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆