zoukankan      html  css  js  c++  java
  • Python | Reverse Slicing of given string倒排并切割字符串

    Sometimes, while working with strings we might have a problem in which we need to perform the reverse slicing of string, i.e slicing the string for certain characters from the rear end. Let’s discuss certain ways in which this can be done.

    Method #1 : Using join() + reversed()
    The combination of above function can be used to perform this particular task. In this, we reverse the string in memory and join the sliced no. of characters so as to return the string sliced from rear end.

    # Python3 code to demonstrate working of
    # Reverse Slicing string 
    # Using join() + reversed()
      
    # initializing string 
    test_str = "GeeksforGeeks"
      
    # printing original string 
    print("The original string is : " + test_str)
      
    # initializing K 
    K = 7
      
    # Using join() + reversed()
    # Reverse Slicing string 
    res = ''.join(reversed(test_str[0:K]))
      
    # printing result 
    print("The reversed sliced string is : " + res)
    Output :
    The original string is : GeeksforGeeks
    The reversed sliced string is : ofskeeG
    

    Method #2 : Using string slicing
    The string slicing can be used to perform this particular task, by using “-1” as the third argument in slicing we can make function perform the slicing from rear end hence proving to be a simple solution.



    # Python3 code to demonstrate working of
    # Reverse Slicing string 
    # Using string slicing
      
    # initializing string 
    test_str = "GeeksforGeeks"
      
    # printing original string 
    print("The original string is : " + test_str)
      
    # initializing K 
    K = 7
      
    # Using string slicing
    # Reverse Slicing string 
    res = test_str[(K-1)::-1]
      
    # printing result 
    print("The reversed sliced string is : " + res)
    Output :
    The original string is : GeeksforGeeks
    The reversed sliced string is : ofskeeG
    

    Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

    To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

  • 相关阅读:
    批量关闭远程计算机
    Tomcat6+IIS6集成及Tomcat负载均衡与Tomcat集群配置
    负载均衡服务器session共享的解决方案
    实现PostgreSQL数据库服务器的负载均衡
    OPENQUERY (TransactSQL)
    Webarok: 用 Web 浏览器控制 Amarok2
    Nginx+tomcat负载均衡session问题解决
    CorelDRAW 编写和运行宏指令
    FB/IB多代事务结构详解对FB事务最好的讲解
    VS2005[C#] 操作 Excel 全攻略
  • 原文地址:https://www.cnblogs.com/weifeng1463/p/14667394.html
Copyright © 2011-2022 走看看