python - 随机大写字符串中的字母
问题描述
我想随机大写或小写字符串中的每个字母。我是在 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
但那我还能怎么做呢?
解决方案
您可以使用str.join
这样的生成器表达式:
from random import choice
sentence = 'Hello World'
print(''.join(choice((str.upper, str.lower))(c) for c in sentence))
样本输出:
heLlo WORLd
推荐阅读
- php - 如何引用同一数组中的数组元素?
- mysql - 仅保留前 5 个高分的 SQL 命令
- r - 如何在变量子集中省略 NA 但其他变量仍然存在?
- python - 字典乱序列表
- java - 带有未知实体和@Generated Annotation 的 MappingException
- javascript - 如何通过 API 调用获取 base64 字符串
- python - 删除扫描/拍摄的医疗文件中的网格
- reactjs - 如何在 Material UI Paper 元素上居中显示表格
- python-3.x - 重置 tqdm 进度条
- python - Keras:输出和输入的梯度作为分类器的输入