python stringstrip方法详解_《python核心编程第二版》练习题——实现strip()函数

  • Post author:
  • Post category:python


strip()函数是python3里对字符串操作的内建函数,它可以自动的去除字符串的首尾的指定所有字符(返回值)。默认是去除空格字符。

下面是自己去实现该函数的代码。

#!/usr/bin/env python

def stringstrip(string1):

length = len(string1)

index = 0

if length == 0:

print(“Input string is no char!”)

return

while True:

if (string1[index] == ‘ ‘):

index += 1

string1 = string1[index:]

continue

print(‘there are %d’ % (index), ‘space begin with string1’)

if index == length-1:

print(‘BAD! All string1 are fill with space ‘)

return

break

index = -1

while True:

if (string1[index] == ‘ ‘):

index -= 1

string1 = string1[:index]

continue

print(‘there are %d’ % (index+1), ‘space reverse with string1’)

break

return string1

if __name__ == “__main__”:

while True:

newstring = stringstrip(input(“Enter your string:”))

print(‘Del space, your new string is ‘ + newstring)



版权声明:本文为weixin_39693971原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。