当前位置:网站首页>Skilled use of slicing operations

Skilled use of slicing operations

2022-06-23 06:29:00 Beauty of algorithm and programming

0 introduction

stay python in , We often intercept the specified index range of a string , It is very complicated to operate with a loop structure , therefore python Provides slicing operations , One line of code can be used to experiment with operations that can only be completed by many loops , It greatly simplifies the process .

1 problem

Using slicing , Achieve one trim() function , Remove the space at the beginning and end of the string .

for example : Remove ‘   HelloWorld     ’ First and last spaces .

2 Method

First step , The first character of a string can be clearly expressed as n=n[1:]; Second parts , The last character of the string can be clearly expressed as n=n[:-1]. Because I don't know the length of the string and the number of leading and trailing spaces , You can use two while loop , When n[0]==’ ( Space )’ when , Remove the leading and trailing spaces in turn , When n[len(n)-1:len(n)]==’ ( Space )’ when , Go out the space at the end , There is no space until the beginning and end , End of cycle .

3 Experimental results and discussion

Through the experiment 、 Practice has proved that the proposed method is effective , Is able to solve the problem raised at the beginning .

Code list 1

def trim(n):
   while n[0]==' ':
       n=n[1:]
   while n[len(n)-1:len(n)]==' ':
       n=n[:-1]
   return n
n=input(' Please enter a string :')
print(trim(n))

4 Conclusion

For the problem of removing the closing space of the string , Propose slicing method , Through many experiments , The method is proved to be effective , The method in this paper makes use of slicing and loop operation to simplify the complex loop structure , It can provide good ideas for more complex loop operations in the future . At the same time, you can also review the definition of functions def sentence , Consolidate what you have learned .

原网站

版权声明
本文为[Beauty of algorithm and programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230446058992.html

随机推荐