在 Python 中旋转字符串 [英] Rotating strings in Python

查看:40
本文介绍了在 Python 中旋转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Python 中将字符串 HELLO 变成 OHELL.但是如果不使用循环就无法旋转它.如何仅用 1-2 行代码编写代码,以便获得所需的模式?

解决方案

您可以切片和添加字符串:

<预><代码>>>>s = '你好'>>>s[-1] + s[:-1]'OHELL'

这给你最后一个字符:

<预><代码>>>>s[-1]'O'

这一切,但最后一个:

<预><代码>>>>s[:-1]'地狱'

最后,用 + 添加它们.

I was trying to make the string HELLO to OHELL in Python. But couldn't get any way to rotate it without working with loops. How to code for it in just 1-2 lines so that I could get the desired pattern?

解决方案

You can slice and add strings:

>>> s = 'HELLO'
>>> s[-1] + s[:-1]
'OHELL'

This gives you the last character:

>>> s[-1]
'O'

and this everything but the last:

>>> s[:-1]
'HELL'

Finally, add them with +.

这篇关于在 Python 中旋转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆