利用切片操作,實現函式,去除字串首尾的0

2021-08-20 20:15:01 字數 664 閱讀 7651

此例使用strip()方法可以很輕鬆的實現,這個**旨在熟悉切片的操作。

python strip()方法

用於移除字串頭尾指定的字元(預設為空格或換行符)或字串行。

注意:該方法只能刪除開頭或是結尾的字元,不能刪除中間部分的字元。

語法strip()方法語法:

str.strip([chars]);

引數chars    移除字串頭尾指定的字串行。

返回值返回移除字串頭尾指定的字元生成的新字串。

python實現的**如下:

def trim(s):

#第乙個for迴圈去除字串前面的0

for i in s:

if i == '0':

s = s[1 : len(s)]

else:

break

#第二個for迴圈去除字串後面的0

for i in range(1, len(s)):

if s[-1] == '0':

s = s[0 : len(s) - 1]

else:

break

print(s)

if __name__ == "__main__":

trim('000000python000')

python使用切片實現去除字串首尾空白字元

測試項為 if trim hello hello print left 測試失敗 elif trim hello hello print right 測試失敗 elif trim hello hello print both 測試失敗 elif trim hello world hello worl...

字串切片slice操作 字串

切片slice操作可以讓我們快速的提取子字串,標準格式為 起始偏移量start 終止偏移量end 步長step 典型操作 操作和說明 示例結果 提取整個字串 abcdef abcdef start 從start索引開始到結尾 abcdef 2 abcdef end 從頭開始到end 1 abcdef...

Python字串切片操作

我們基本上都知道python的序列物件都是可以用索引號來引用的元素的,索引號可以是正數由0開始從左向右,也可以是負數由 1開始從右向左。在python中對於具有序列結構的資料來說都可以使用切片操作,需注意的是序列物件某個索引位置返回的是乙個元素,而切片操作返回是和被切片物件相同型別物件的副本。今天戀...