python学习笔记:字符串
string类型由多个字符组成,可以把字符串看成一个整体,也可以取得字符串中的任何一个部分。
函数len() 返回字符串的长度

>>> address = 'www.baidu.com' >>> len(address) 13
用for语句遍历字符串
从第一个字符开始,按照顺序读取字符,然后在做相应的处理,直到最后一个字符,这个处理过程我们称为遍历。

>>> for char in address : ... print char
字符串片断
字符串的一部分叫做片断,操作符 [n:m] 返回字符串的一部分,从第n个字符开始到第m个字符结束,包括第n个,但是不包括第m个。只写m表示从索引0开始,只写n表示从n到最后一个字符。

>>> os = "linux unix freeBSD" >>> print os[0:5] linux >>> print os[6:10] unix >>> print os[:5] linux >>> print os[11:] freeBSD
我们知道字符串是不可变的,如果我们修改其中的一个字符,最好的操作就是取字符串的一部分和添加或更换的字符串相加,形成一个新的字符串:

>>> s = "use Python!" >>> new_s = s[0:3]+" p"+s[5:] >>> print new_s use python!
如果仅仅只是替换一个子字符串的话,可以用字符串的replace()方法来实现:

>>> S = "spammy" >>> S = S.replace('mm','xx') >>> print S spaxxy
字符串模块
字符串模块string包含一些处理字符串的函数。在用到模块前必须先引入:import string
字符串模块中包含一个名为find的查找字符的函数:

>>> yourname = "your name is limingming" >>> import string >>> index = string.find(yourname,"m") >>> print index 7
程序中常常需要判断字符是大写还是小写,或者判断是字符还是数字。string模块中提供了几个比较有用的常量字符串:
所有的小写字母string.lowercase 所有的大写字母string.uppercase 从0到9的数字string.digits

>>> import string >>> print string.lowercase abcdefghijklmnopqrstuvwxyz >>> print string.uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ >>> print string.digits 0123456789
我们可以利用这几个常量字符串,编写一个是否为小写的函数

import string def isLowercase(char): return string.find(string.lowercase,char) != -1

import string def isLowercase(char): return char in string.lowercase

import string def isLowercase(char): return 'a' <= char <='z'
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤