python-- string reversal --while, for, sliced

python notes - to reverse a string

To reverse a string --while, for, sliced

  • while

    mess = "海上月是天上月,心上人是眼前人。"
    list_mess = []    #创建列表
    index = len(mess)-1
    while index >= 0 :
        list_mess.append(mess[index]) #将字符添加到列表
        index -= 1
    new_mess = ''.join(list_mess) #以空格拼接字符形成新字符串
    print(new_mess)
  • for - reversed for reversing

    mess = "海上月是天上月,心上人是眼前人。"
    list_mess = []
    for i in reversed(mess):
        list_mess.append(i)
    new_mess = ''.join(list_mess)
    print(new_mess)
  • for - range for reversing

    mess = "海上月是天上月,心上人是眼前人。"
    list_mess = []
    for i in range(len(mess)-1,-1,-1):
        list_mess.append(mess[i])
    new_mess = ''.join(list_mess)
    print(new_mess)
  • Slice - the most simple way

    mess = "海上月是天上月,心上人是眼前人。"
    print(mess[::]) #正序
    print(mess[::-1])   #反序

Guess you like

Origin www.cnblogs.com/lgj85376/p/11907191.html