Computer >> Máy Tính >  >> Lập trình >> Python

Cắt chuỗi trong Python để xoay một chuỗi

Một chuỗi được đưa ra, nhiệm vụ của chúng ta là cắt chuỗi thành hai chiều. Một theo chiều kim đồng hồ và một ngược chiều kim đồng hồ.

1. Trái (Hoặc ngược chiều kim đồng hồ) xoay chuỗi đã cho theo d phần tử (trong đó d <=n).

2. Phải (Hoặc theo chiều kim đồng hồ) xoay chuỗi đã cho theo d phần tử (trong đó d <=n).

Ví dụ

Input: string = "pythonprogram"
d = 2
Output: Left Rotation: thonprogrampy
Right Rotation: ampythonprogr

Thuật toán

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.

Mã mẫu

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)

Đầu ra

Enter String ::> pythonprogram
Left Rotation: thonprogrampy
Right Rotation: ampythonprogr