Python 中的字符串切片旋转字符串
给定一个字符串,我们的任务是对字符串进行两种类型的切片操作。一是顺时针,另一个是逆时针。
1. 逆时针(或逆时针)旋转给定的字符串 d 个元素(其中 d <= n)。
2. 顺时针(或顺时针)旋转给定的字符串 d 个元素(其中 d <= n)。
示例
Input: string = "pythonprogram" d = 2 Output: Left Rotation: thonprogrampy Right Rotation: ampythonprogr
算法
Step 1: Enter string. Step 2: Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ]. Step 3: Now concatenate these two parts second + first accordingly.
示例代码
def rotate(input,d):
# Slice string in two parts for left and right
Lfirst = input[0 : d]
Lsecond = input[d :]
Rfirst = input[0 : len(input)-d]
Rsecond = input[len(input)-d : ]
print ("Left Rotation : ", (Lsecond + Lfirst) )
print ("Right Rotation : ", (Rsecond + Rfirst) )
# Driver program
if __name__ == "__main__":
str = input("Enter String ::>")
d=2
rotate(str,d)输出
Enter String ::> pythonprogram Left Rotation: thonprogrampy Right Rotation: ampythonprogr
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP