给定一个字符串:
s = 'The quick brown fox jumps over the lazy dog'
如何随机选择一个令牌,交换该令牌中的两个字母,并返回带有修改令牌的字符串?例如(*)
:
The quick brown fxo jumps over the lazy dog
在上面的示例中,随机选择令牌fox
,并交换两个字符。你知道吗
到目前为止,我试图:
def swap_letters(string):
s = list(string)
s[0], s[len(s)-1] = s[len(s)-1].upper(), s[0].lower()
string = ''.join(s)
return string
def foo(a_string):
a_string_lis = a_string.split()
token = random.choice(a_string_lis)
return swap_letters(token)
然而,我得到超过2个字母转置,我不知道如何保持在字符串内的令牌顺序。你知道如何以更具Python性的方式获得(*)
吗?你知道吗
您可以使用
str.replace
方法:你可以这样做:
输出
更新
对于长度为
1
的字符串,上面的代码失败,类似这样的代码应该可以修复它:相关问题 更多 >
编程相关推荐