【发布时间】:2019-03-27 07:19:03
【问题描述】:
我想将字符串中的每个字母随机大写或小写。我是在 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
但是我还能怎么做呢?
【问题讨论】:
-
使用另一个容器,例如
list,然后从中创建字符串。或者,逐步创建一个新的 sting -
您始终可以创建一个带有随机大写和小写字母的新字符串。
标签: python python-3.x uppercase lowercase