简体   繁体   English

Function 将字符串的每个第一个字符移动到 Python 中的末尾

[英]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.该任务包括完成 function ,它接受一个字符串,并以大写形式返回给定字符串的旋转数组。 This function moves each first character of the string to the end, and stops once the string returns to its original state as below:此 function 将字符串的每个第一个字符移动到末尾,并在字符串返回到其原始 state 时停止,如下所示:

'cat'
'atc'
'tca'

The problem is that my code returns ['atc', 'atc', 'atc'] .问题是我的代码返回['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]"问题出在“switch = returned_text[-1:] + returned_text[-1]”

You are reversing the variable "returned_text" 3 times.您正在反转变量“returned_text”3 次。 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.由于该变量根本没有改变,只接受文本并将其更改为大写,所以没有任何变化,你会得到同样的东西打印 3 次。

To make this work, you would need to change the returned_text variable.要完成这项工作,您需要更改 returned_text 变量。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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