当前位置:网站首页>熟练利用切片操作
熟练利用切片操作
2022-06-23 04:46:00 【算法与编程之美】
0 引言
在python中,我们经常会对字符串的指定索引范围进行截取,使用循环结构对其操作十分复杂,因此python提供了切片操作,一行代码就可以了实验很多循环才能完成的操作,大大简化了过程。
1 问题
利用切片操作,实现一个trim()函数,去除字符串首尾的空格。
例如:去除‘ HelloWorld ’首尾的空格。
2 方法
第一步,将字符串第一个字符利用切片的形式清楚可表示为n=n[1:];第二部,将字符串最后一个字符利用切片的形式清楚可表示为n=n[:-1]。由于不知道字符串长度以及首尾空格的个数,可以利用两个while循环,当n[0]==’ (空格)’时,去除首端的空格依次清除首尾的空格,当n[len(n)-1:len(n)]==’ (空格)’时,出去尾端的空格,直到首尾都不是空格,结束循环。
3 实验结果与讨论
通过实验、实践等证明提出的方法是有效的,是能够解决开头提出的问题。
代码清单 1
| def trim(n): while n[0]==' ': n=n[1:] while n[len(n)-1:len(n)]==' ': n=n[:-1] return n n=input('请输入一个字符串:') print(trim(n)) |
4 结语
针对去除字符串收尾空格问题,提出切片方法,通过多次实验,证明该方法是有效的,本文的方法利用了切片和循环操作简化了复杂的循环结构,能够为以后更加复杂的循环操作提供良好的思路。同时也能够复习到定义函数的def语句,巩固所学习过的内容。
边栏推荐
- Jour 13 Projet de santé mentale - chapitre 13
- Pat class B 1020 Moon Cake
- Fraction to recursing decimal
- 十一、纺织面料下架功能的实现
- 【已解决】“The Unity environment took too long to respond. Make sure that :\n“
- 【Leetcode】431. Encode N-ary Tree to Binary Tree(困难)
- Add and multiply two polynomials using linked list
- Pat class B 1015 C language
- What is a PDCA cycle? How to integrate PDCA cycle and OKR
- Pat class B 1025 reverse linked list
猜你喜欢

Pyqt5 setting window top left Icon

Design scheme of Small PLC based on t5l1

Redis 哨兵

Day_04 傳智健康項目-預約管理-套餐管理

微软面试题:打印折纸的折痕

【Vivado那些事儿】XilinxCEDStore介绍

Runc symbolic link mount and container escape vulnerability alert (cve-2021-30465)

(1) Basic learning - Common shortcut commands of vim editor

Learning Tai Chi Maker - esp8226 (11) distribution network with WiFi manager Library

Detailed explanation of redis persistence, master-slave and sentry architecture
随机推荐
Day_ 13 smart health project - Chapter 13
Summary of ant usage (I): using ant to automatically package apk
求二叉树最宽的层有多少个节点
[database backup] complete the backup of MySQL database through scheduled tasks
Microsoft interview question: creases in origami printing
Day_ 01 smart communication health project - project overview and environmental construction
Day_05 传智健康项目-预约管理-预约设置
Day_12 传智健康项目-JasperReports
Pat class B 1026 program running time
Extend your kubernetes API using the aggregation API
Given a node of a binary tree, return the successor node of the node
Simple about fastdfs
Pat class B 1015 C language
Docker实战 -- 部署Redis集群与部署微服务项目
Kotlin collaboration +retro most elegant network request use
Remove the influence of firewall and virtual machine on live555 startup IP address
WordPress aawp 3.16 cross site scripting
Redis 哨兵
Pat class B 1024 scientific notation C language
ant使用总结(一):使用ant自动打包apk