zoukankan      html  css  js  c++  java
  • 字符串的切片

    切片操作(slice)可以从一个字符串中获取子字符串(字符串的一部分)。我们使用一对方括号、起始偏移量start、终止偏移量end 以及可选的步长step 来定义一个分片。

    格式: [start:end:step]

    • [:] 提取从开头(默认位置0)到结尾(默认位置-1)的整个字符串
    •  [start:] 从start 提取到结尾
    •  [:end] 从开头提取到end - 1
    •  [start:end] 从start 提取到end - 1
    •  [start:end:step] 从start 提取到end - 1,每step 个字符提取一个
    •  左侧第一个字符的位置/偏移量为0,右侧最后一个字符的位置/偏移量为-1
    举例:
    输入一个字符串,返回倒序排序的结果,:如:‘abcdef’ 返回:'fedcba'
    复制代码
    #方式一:将字符串翻转,步长设为-1
    def re_sort():
        s = input('请输入一串字符串:>>')
        return s[::-1] #从开头到结尾步长为-1
    # obj = re_sort()
    # print(obj)
    
    #方式二:借助列表进行翻转
    def re_sort2():
        s = input('请输入一串字符串:>>')
        li = []
        for i in s:
            li.append(i)
        li.reverse()  #将列表反转
        return ''.join(li)  #将列表转化成字符串
    obj2 = re_sort2()
    print(obj2)
    复制代码
  • 相关阅读:
    LeetCode 121. Best Time to Buy and Sell Stock
    LeetCode 221. Maximal Square
    LeetCode 152. Maximum Product Subarray
    LeetCode 53. Maximum Subarray
    LeetCode 91. Decode Ways
    LeetCode 64. Minimum Path Sum
    LeetCode 264. Ugly Number II
    LeetCode 263. Ugly Number
    LeetCode 50. Pow(x, n)
    LeetCode 279. Perfect Squares
  • 原文地址:https://www.cnblogs.com/chairlin/p/12322959.html
Copyright © 2011-2022 走看看