简体   繁体   中英

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

The task consists to complete the function which takes a string, and returns an array with rotation of the given string, in uppercase. This function moves each first character of the string to the end, and stops once the string returns to its original state as below:

'cat'
'atc'
'tca'

The problem is that my code returns ['atc', 'atc', 'atc'] . Where's the problem?

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
 

The problem is in "switch = returned_text[-1:] + returned_text[-1]"

You are reversing the variable "returned_text" 3 times. Since that variable doesn't change at all and only takes in the text and changes it to uppercase, nothing is changing and you will get the same thing printed three times.

To make this work, you would need to change the returned_text variable. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM