字符串的切片
切片操作(slice)可以從一個字符串中獲取子字符串(字符串的一部分)。我們使用一對方括號、起始偏移量start、終止偏移量end 以及可選的步長step 來定義一個分片。
格式: [start:end:step]
- ?[:] 提取從開頭(默認位置0)到結(jié)尾(默認位置-1)的整個字符串
- ?[start:] 從start 提取到結(jié)尾
- ?[:end] 從開頭提取到end - 1
- ?[start:end] 從start 提取到end - 1
- ?[start:end:step] 從start 提取到end - 1,每step 個字符提取一個
- ?左側(cè)第一個字符的位置/偏移量為0,右側(cè)最后一個字符的位置/偏移量為-1
輸入一個字符串,返回倒序排序的結(jié)果,:如:‘a(chǎn)bcdef’ 返回:'fedcba' #方式一:將字符串翻轉(zhuǎn),步長設(shè)為-1 def re_sort():s = input('請輸入一串字符串:>>')return s[::-1] #從開頭到結(jié)尾步長為-1 # obj = re_sort() # print(obj)#方式二:借助列表進行翻轉(zhuǎn) def re_sort2():s = input('請輸入一串字符串:>>')li = []for i in s:li.append(i)li.reverse() #將列表反轉(zhuǎn)return ''.join(li) #將列表轉(zhuǎn)化成字符串 obj2 = re_sort2() print(obj2)
轉(zhuǎn)載于:https://www.cnblogs.com/qiangshenqi/p/9043932.html
總結(jié)
- 上一篇: 2.13Nmap
- 下一篇: hdu 2191 悼念512汶川大地震遇