简体   繁体   English

Python - 如何按 X 量移动字符串中的字符

[英]Python - How to move characters in string by X amount

In python how can I move characters in string by x amount?在python中,如何按x量移动字符串中的字符?

For example lets say the input was "hello"例如,假设输入是“你好”

How can I move each character in the string by 1 so the output I get I get is: "ohell"如何将字符串中的每个字符移动 1,以便我得到的输出是:“ohell”

You could use:你可以使用:

my_string = 'hello'
my_string = my_string[-1] + my_string[:-1]
print(my_string)

Output输出

ohell

my_string[-1] selects the last character in the string ( 'o' ), and my_string[:-1] selects all of the string excluding the last character ( 'hell' ). my_string[-1]选择字符串中的最后一个字符 ( 'o' ), my_string[:-1]选择除最后一个字符 ( 'hell' ) 之外的所有字符串。

To move by x amount you could use:要按 x 量移动,您可以使用:

my_string = my_string[-x:] + my_string[:-x]

my_string[-x:] selects the last x characters in the string, and my_string[:-x] selects all of the string excluding the last x characters. my_string[-x:]选择字符串中的最后 x 个字符,而my_string[:-x]选择除最后 x 个字符之外的所有字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM