[原创]Python入门教程2. 字符串基本操作【运算、格式化输出、常用函数】


Posted in Python onOctober 29, 2018

前面简单介绍了Python基本运算,这里再来简单讲述一下Python字符串相关操作

1. 字符串表示方法

>>> "3water.com" #字符串使用单引号(')或双引号(")表示
'3water.com'
>>> '3water.com'
'3water.com'
>>> "www."+"3water"+".net" #字符串可以用“+”号连接
'3water.com'
>>> "#"*10 #字符串可以使用“*”来代表重复次数
'##########'
>>> "What's your name?" #单引号中可以直接使用双引号,同理双引号中也可以直接使用单引号
"What's your name?"
>>> path = r"C:\newfile" #此处r开头表示原始字符串,里面放置的内容都是原样输出
>>> print(path)
C:\newfile

2. 字符串运算

>>> str1 = "python test"
>>> "test" in str1 #这里in用来判断元素是否在序列中
True
>>> len(str1) #这里len()函数求字符串长度
11
>>> max(str1)
'y'
>>> min(str1)
' '

3. 字符串格式化输出(这里重点讲format函数)

>>> "I like %s" % "python" #使用%进行格式化输出的经典表示方式
'I like python'
>>> dir(str) #列出字符串所有属性与方法
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

format(*args,**kwargs) 采用*args赋值

>>> str = "I like {1} and {2}" #这里{1}表示占位符(注意:这里得从{0}开始)
>>> str.format("python","PHP")
Traceback (most recent call last):
 File "<pyshell#5>", line 1, in <module>
  str.format("python","PHP")
IndexError: tuple index out of range
>>> str = "I like {0} and {1}"
>>> str.format("python","PHP")
'I like python and PHP'
>>> "I like {1} and {0}".format("python","PHP")
'I like PHP and python'
>>> "I like {0:20} and {1:>20}".format("python","PHP")#{0:20}表示第一个位置占据20个字符,并且左对齐。{1:>20}表示第二个位置占据20个字符,且右对齐
'I like python        and         PHP'
>>> "I like {0:.2} and {1:^10.2}".format("python","PHP")#{0:.2}表示第一个位置截取2个字符,左对齐。{1:^10.2}表示第二个位置占据10个字符,且截取2个字符,^表示居中
'I like py and   PH  '
>>> "age: {0:4d} height: {1:6.2f}".format("32","178.55") #这里应该是数字,不能用引号,否则会被当作字符串而报错!
Traceback (most recent call last):
 File "<pyshell#0>", line 1, in <module>
  "age: {0:4d} height: {1:6.2f}".format("32","178.55")
ValueError: Unknown format code 'd' for object of type 'str'
>>> "age: {0:4d} height: {1:8.2f}".format(32,178.5523154) #这里4d表示长度为4个字符的整数,右对齐。8.2f表示长度为8,保留2位小数的浮点数,右对齐。
'age:  32 height:  178.55'

format(*args,**kwargs) 采用**kwargs赋值

>>> "I like {str1} and {str2}".format(str1 = "python",str2 ="PHP")
'I like python and PHP'
>>> data = {"str1":"PHP","str2":"Python"}
>>> "I like {str1} and {str2}".format(**data)
'I like PHP and Python'

小结:对齐方式为:

左对齐
> 右对齐
^ 居中对齐

4. 字符串函数

>>> # isalpha()判断字符串是否全部为字母
>>> str1 = "I like python" #这里str1里面有空格
>>> str1.isalpha()
False
>>> str2 = "pythonDemo" #这里为全部是字母
>>> str2.isalpha()
True

>>> # split()分割字符串
>>> smp = "I like Python"
>>> smp.split(" ")
['I', 'like', 'Python']

>>> # strip()去除字符串两端空格 ,类似的,lstrip去除左侧空格,rstrip去除右侧空格
>>> strDemo = "  python demo  "
>>> strDemo.strip() #类似于php中的trim()函数
'python demo'
>>> "****python**".strip("*") #strip()函数还可删除指定字符
'python'

字符串常用函数【转换、判断】

split() 分割字符串
strip() 去除字符串两端空格
upper() 转大写
lower() 转小写
capitalize() 首字母转大写
title() 转换为标题模式(字符串中所有首字母大写,其他字母小写)
swapcase() 大写转小写,小写转大写(如:"I Like Python".swapcase() 得到i lIKE pYTHON)
isupper() 判断字母是否全部为大写
islower() 判断字母是否全部为小写
istitle() 判断是否为标题模式(字符串中所有单词首字母大写,其他小写)
isalpha() 判断字符串是否全部为字母
isdigit() 判断字符串是否全部为数字
isalnum() 判断字符串是否仅包含字母与数字
>>> #字符串拼接(对于+不适用的情况下可以使用)
>>> smp = "I like Python"
>>> c = smp.split(" ")
>>> c = "I like python".split()
>>> type(c) #这里检测类型,可以看到c为列表
<class 'list'>
>>> "*".join(c)
'I*like*Python'
>>> " ".join(c)
'I like Python'
>>> " ".join(["I","Like","python"]) #这里可以直接使用列表作为join函数的参数
'I Like python'
>>> " ".join("abcd") #也可直接使用字符串作为join函数的参数
'a b c d'

>>> # count()函数统计指定字符串出现次数
>>> "like python,learn python".count("python")
2

>>> # find()函数查找指定字符串出现位置
>>> "python Demo".find("python")
0
>>> "python Demo".find("Demo")
7

>>> # replace(old,new)函数替换指定字符串(old)为新字符串(new)
>>> "I like php".replace("php","python")
'I like python'

简单入门教程~

基本一看就懂~O(∩_∩)O~

未完待续~~欢迎讨论!!

Python 相关文章推荐
解决uWSGI的编码问题详解
Mar 24 Python
python opencv 图像拼接的实现方法
Jun 27 Python
Python 等分切分数据及规则命名的实例代码
Aug 16 Python
100行Python代码实现每天不同时间段定时给女友发消息
Sep 27 Python
导入tensorflow:ImportError: libcublas.so.9.0 报错
Jan 06 Python
Python类继承和多态原理解析
Feb 05 Python
如何在django中添加日志功能
Feb 06 Python
django admin 根据choice字段选择的不同来显示不同的页面方式
May 13 Python
利用python下载scihub成文献为PDF操作
Jul 09 Python
Python 随机按键模拟2小时
Dec 30 Python
详解pandas映射与数据转换
Jan 22 Python
Python爬虫入门案例之爬取二手房源数据
Oct 16 Python
pycharm执行python时,填写参数的方法
Oct 29 #Python
解决Pycharm下面出现No R interpreter defined的问题
Oct 29 #Python
解决Pycharm运行时找不到文件的问题
Oct 29 #Python
解决Mac下首次安装pycharm无project interpreter的问题
Oct 29 #Python
解决pycharm运行时interpreter为空的问题
Oct 29 #Python
在Pycharm中项目解释器与环境变量的设置方法
Oct 29 #Python
mac PyCharm添加Python解释器及添加package路径的方法
Oct 29 #Python
You might like
SMARTY学习手记
2007/01/04 PHP
php使用mkdir创建多级目录入门例子
2014/05/10 PHP
ThinkPHP实现将本地文件打包成zip下载
2014/06/26 PHP
thinkphp在模型中自动完成session赋值示例代码
2014/09/09 PHP
Ubuntu中启用php的mail()函数并解决发送邮件速度慢问题
2015/03/27 PHP
php递归函数三种实现方法及如何实现数字累加
2015/08/07 PHP
php实现阳历阴历互转的方法
2015/10/28 PHP
php 解析xml 的四种方法详细介绍
2016/10/26 PHP
document.all与WEB标准
2020/05/13 Javascript
js函数调用常用方法详解
2012/12/03 Javascript
javascript加号&quot;+&quot;的二义性说明
2013/03/04 Javascript
js 获取input点选按钮的值的方法
2014/04/14 Javascript
jQuery仿淘宝网产品品牌隐藏与显示效果
2015/09/01 Javascript
很不错的两款Bootstrap Icon图标选择组件
2016/01/28 Javascript
扩展jquery easyui tree的搜索树节点方法(推荐)
2016/10/28 Javascript
html判断当前页面是否在iframe中的实例
2016/11/30 Javascript
Javascript设计模式之装饰者模式详解篇
2017/01/17 Javascript
基于Bootstrap的网页设计实例
2017/03/01 Javascript
protractor的安装与基本使用教程
2017/07/07 Javascript
详解vue 模版组件的三种用法
2017/07/21 Javascript
基于vue v-for 循环复选框-默认勾选第一个的实现方法
2018/03/03 Javascript
详解VUE中常用的几种import(模块、文件)引入方式
2018/07/03 Javascript
关于微信小程序登录的那些事
2019/01/08 Javascript
Vue.extend 编程式插入组件的实现
2019/11/18 Javascript
[01:32]DOTA2 2015国际邀请赛中国区预选赛第四日战报
2015/05/29 DOTA
python安装twisted的问题解析
2018/08/21 Python
Python中修改字符串的四种方法
2018/11/02 Python
PyCharm如何导入python项目的方法
2020/02/06 Python
Mio Skincare美国官网:身体紧致及孕期身体护理
2017/03/05 全球购物
ZWILLING双立人英国网上商店:德国刀具锅具厨具品牌
2018/05/15 全球购物
Under Armour西班牙官网:美国知名的高端功能性运动品牌
2018/12/12 全球购物
犹他州最古老的体育用品公司:Al’s
2020/12/18 全球购物
javascript实现用户必须勾选协议实例讲解
2021/03/24 Javascript
酒店应聘自荐信
2013/11/09 职场文书
涨工资申请书应该怎么写?
2019/07/08 职场文书
Redis可视化客户端小结
2021/06/10 Redis