開始使用免費開始

位移字串

你將要建立一個產生器(generator)。給定一個字串,它會依指定的位移量 shift 產生一連串位移後的字元。舉例來說,字串 'sushi' 在向右位移 2 個位置(shift = 2)時,會產生序列 'h''i''s''u''s'。當向左位移 2 個位置(shift = -2)時,產生的序列會是 's''h''i''s''u'

提示:使用 % 運算子在有效索引之間循環。將它用在正數或負數上都會得到非負的餘數,這在位移索引時很有幫助。

例如,考慮變數 string = 'python',其字串長度為 6

  • 2 % 6 = 2(因此,string[2 % 6]t
  • 0 % 6 = 0(因此,string[0 % 6]p
  • -2 % 6 = 4(因此,string[-2 % 6]o

本練習屬於課程

Python 程式面試題實作練習

檢視課程

練習說明

  • 使用提供的變數 len_string 來迴圈走訪字串的索引。
  • 找出在套用位移後,對應到該索引的字元是什麼。
  • 建立一個產生器,將字串 'DataCamp' 向右位移 3 個位置(也就是 "ampDataC")。
  • 使用該產生器建立一個新的字串並將它印出。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def shift_string(string, shift):
    len_string = len(string)
    # Loop over the indices of a string
    for idx in ____:
        # Find which character will correspond to the index.
        ____ ____[____]
       
# Create a generator
gen = ____

# Create a new string using the generator and print it out
string_shifted = ''.____
print(string_shifted)
編輯並執行程式碼