[原创]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 相关文章推荐
详解Python中的__getitem__方法与slice对象的切片操作
Jun 27 Python
python使用正则表达式的search()函数实现指定位置搜索功能
Nov 10 Python
Python实现PS图像调整颜色梯度效果示例
Jan 25 Python
python pytest进阶之fixture详解
Jun 27 Python
django echarts饼图数据动态加载的实例
Aug 12 Python
用Python爬取QQ音乐评论并制成词云图的实例
Aug 24 Python
python检测服务器端口代码实例
Aug 31 Python
python实现的多任务版udp聊天器功能案例
Nov 13 Python
使用PyCharm安装pytest及requests的问题
Jul 31 Python
python实现经纬度采样的示例代码
Dec 10 Python
Python爬取梨视频的示例
Jan 29 Python
anaconda升级sklearn版本的实现方法
Feb 22 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
php根据分类合并数组的方法实例详解
2013/11/06 PHP
Yii2压缩PHP中模板代码的输出问题
2018/08/28 PHP
jQuery实现的类flash菜单效果代码
2010/05/17 Javascript
发布一个基于javascript的动画类 Fx.js
2010/11/05 Javascript
JavaScript高级程序设计(第3版)学习笔记 概述
2012/10/11 Javascript
JS 实现Json查询的方法实例
2013/04/12 Javascript
js实现点小图看大图效果的思路及示例代码
2013/10/28 Javascript
开发中可能会用到的jQuery小技巧
2014/03/07 Javascript
JavaScript使用push方法添加一个元素到数组末尾用法实例
2015/04/06 Javascript
jquery实现很酷的网页顶部图标下拉菜单效果
2015/08/22 Javascript
Bootstrap表单组件教程详解
2016/04/26 Javascript
封装的dialog插件 基于bootstrap模态对话框的简单扩展
2016/08/10 Javascript
Bootstarp 基础教程之表单部分实例代码
2017/02/03 Javascript
Bootstrap显示与隐藏简单实现代码
2017/03/06 Javascript
VS Code转换大小写、修改选中文字或代码颜色的方法
2017/12/15 Javascript
5个你不知道的JavaScript字符串处理库(小结)
2020/06/01 Javascript
基于原生js实现判断元素是否有指定class名
2020/07/11 Javascript
详解JavaScript作用域 闭包
2020/07/29 Javascript
vue router返回到指定的路由的场景分析
2020/11/10 Javascript
python显示生日是星期几的方法
2015/05/27 Python
Python连接DB2数据库
2016/08/27 Python
win10环境下python3.5安装步骤图文教程
2017/02/03 Python
Python实现去除列表中重复元素的方法总结【7种方法】
2019/02/16 Python
python钉钉机器人运维脚本监控实例
2019/02/20 Python
python点击鼠标获取坐标(Graphics)
2019/08/10 Python
详解python内置模块urllib
2020/09/09 Python
python super()函数的基本使用
2020/09/10 Python
一款CSS3实现多功能下拉菜单(带分享按)的教程
2014/11/05 HTML / CSS
纯css3制作煽动翅膀的蝴蝶的示例
2018/04/23 HTML / CSS
Johnston & Murphy官网: 约翰斯顿·墨菲牛津总统鞋
2018/01/09 全球购物
英国儿童设计师服装和玩具购物网站:Zac & Lulu
2020/10/19 全球购物
房地产出纳岗位职责
2013/12/01 职场文书
学习三严三实对照检查材料思想汇报
2014/09/22 职场文书
2014年学校教学工作总结
2014/12/06 职场文书
保护动物的宣传语
2015/07/13 职场文书
mysql 8.0.27 绿色解压版安装教程及配置方法
2022/04/20 MySQL