繁体   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