簡體   English   中英

Function 將字符串的每個第一個字符移動到 Python 中的末尾

[英]Function moving each first character of the string to the end in Python

該任務包括完成 function ,它接受一個字符串,並以大寫形式返回給定字符串的旋轉數組。 此 function 將字符串的每個第一個字符移動到末尾,並在字符串返回到其原始 state 時停止,如下所示:

'cat'
'atc'
'tca'

問題是我的代碼返回['atc', 'atc', 'atc'] 問題出在哪里?

def scrolling_text(text):
    returned_text = text.upper()
    list_of_switchs = []
    text_length = len(text)
    while len(list_of_switchs) <= text_length:
        switch = returned_text[-1:] + returned_text[:-1]
        list_of_switchs.append(switch)
        if len(list(list_of_switchs)) == text_length:
            break
    return list_of_switchs
 

問題出在“switch = returned_text[-1:] + returned_text[-1]”

您正在反轉變量“returned_text”3 次。 由於該變量根本沒有改變,只接受文本並將其更改為大寫,所以沒有任何變化,你會得到同樣的東西打印 3 次。

要完成這項工作,您需要更改 returned_text 變量。 嘗試這個:

def scrolling_text(text):
  returned_text = text.upper()
  list_of_switchs = []
  text_length = len(text)
  
  while len(list_of_switchs) <= text_length:
    switch = returned_text[-1:] + returned_text[:-1]
    list_of_switchs.append(switch)
    returned_text = switch
    if len(list(list_of_switchs)) == text_length:
      break
  return list_of_switchs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM