use*_*890 14 python lowercase python-3.x uppercase
我想随机大写或小写字符串中的每个字母.我是新手在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)
Run Code Online (Sandbox Code Playgroud)
并得到错误:TypeError:'str'对象不支持项目分配
但那么我怎么能这样做呢?
blh*_*ing 21
您可以使用这样str.join的生成器表达式:
from random import choice
sentence = 'Hello World'
print(''.join(choice((str.upper, str.lower))(c) for c in sentence))
Run Code Online (Sandbox Code Playgroud)
样本输出:
heLlo WORLd
Run Code Online (Sandbox Code Playgroud)
构建一个新字符串.
这是一个对原始代码几乎没有变化的解决方案:
>>> import random
>>>
>>> def randomcase(s):
...: result = ''
...: for c in s:
...: case = random.randint(0, 1)
...: if case == 0:
...: result += c.upper()
...: else:
...: result += c.lower()
...: return result
...:
...:
>>> randomcase('Hello Stackoverflow!')
>>> 'hElLo StaCkoVERFLow!'
Run Code Online (Sandbox Code Playgroud)
编辑:删除我的oneliners因为我喜欢blhsing更好.
| 归档时间: |
|
| 查看次数: |
1709 次 |
| 最近记录: |