您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在python中的字符串中交换字母

在python中的字符串中交换字母

您可以将其缩短为

def rotate(strg,n):
    return strg[n:] + strg[:n]

并简单地使用负索引来“向右”旋转:

>>> rotate("hello", 2)
'llohe'
>>> rotate("hello", -1)
'ohell'
>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 4)
'ohell'
>>> rotate("hello", -3)
'llohe'
>>> rotate("hello", 6)  # same with -6: no change if n > len(strg)
'hello'

如果即使在超过字符串长度后仍要保持旋转,请使用

def rotate(strg,n):
    n = n % len(strg)
    return strg[n:] + strg[:n]

所以你得到

>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 6)
'elloh'
python 2022/1/1 18:41:27 有315人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶