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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便