[原创]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 thread 并发且顺序运行示例
Apr 09 Python
python实现图片批量剪切示例
Mar 25 Python
使用python实现生成用户信息
Mar 20 Python
python3 判断列表是一个空列表的方法
May 04 Python
Python 隐藏输入密码时屏幕回显的实例
Feb 19 Python
python通过对字典的排序,对json字段进行排序的实例
Feb 27 Python
Pycharm连接gitlab实现过程图解
Sep 01 Python
Python requests接口测试实现代码
Sep 08 Python
Python如何急速下载第三方库详解
Nov 02 Python
python 爬虫如何实现百度翻译
Nov 16 Python
Python3使用tesserocr识别字母数字验证码的实现
Jan 29 Python
python 用递归实现通用爬虫解析器
Apr 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
Flash空降上海 化身大魔王接受挑战
2020/03/02 星际争霸
ExtJS Window 最小化的一种方法
2009/11/18 Javascript
javascript+html5实现绘制圆环的方法
2015/07/28 Javascript
Node.js的基本知识简单汇总
2016/09/19 Javascript
基于JS实现翻书效果的页面切换样式
2017/02/16 Javascript
JavaScript实现获取远程的html到当前页面中
2017/03/26 Javascript
VUE Error: getaddrinfo ENOTFOUND localhost
2018/05/03 Javascript
JS实现的判断方法、变量是否存在功能示例
2020/03/28 Javascript
微信小程序使用wxParse解析html的实现示例
2018/08/30 Javascript
Vue.js 事件修饰符的使用教程
2018/11/01 Javascript
Vue 全家桶实现移动端酷狗音乐功能
2018/11/16 Javascript
为vue项目自动设置请求状态的配置方法
2019/06/09 Javascript
nodejs对项目下所有空文件夹创建gitkeep的方法
2019/08/02 NodeJs
利用JS响应式修改vue实现页面的input值
2019/09/02 Javascript
JavaScript简单编程实例学习
2020/02/14 Javascript
Vue项目移动端滚动穿透问题的实现
2020/05/19 Javascript
easyUI 实现的后台分页与前台显示功能示例
2020/06/01 Javascript
Python中删除文件的程序代码
2011/03/13 Python
Python 高级专用类方法的实例详解
2017/09/11 Python
完美解决python中ndarray 默认用科学计数法显示的问题
2018/07/14 Python
python实现多进程代码示例
2018/10/31 Python
Python 写入训练日志文件并控制台输出解析
2019/08/13 Python
Python坐标线性插值应用实现
2019/11/13 Python
python使用itchat模块给心爱的人每天发天气预报
2019/11/25 Python
python基于event实现线程间通信控制
2020/01/13 Python
Python变量作用域LEGB用法解析
2020/02/04 Python
详解在Python中使用Torchmoji将文本转换为表情符号
2020/07/27 Python
用Python自动清理电脑内重复文件,只要10行代码(自动脚本)
2021/01/09 Python
使用HTML5 Geolocation实现一个距离追踪器
2018/04/09 HTML / CSS
HTML5 manifest离线缓存的示例代码
2018/08/08 HTML / CSS
瑞贝卡·泰勒官方网站:Rebecca Taylor
2016/09/24 全球购物
荣耀俄罗斯官网:HONOR俄罗斯
2020/10/31 全球购物
数控技术专科生自我评价
2014/01/08 职场文书
中秋节国旗下演讲稿
2014/09/05 职场文书
晚会开幕词范文
2016/03/04 职场文书
mysql实现将字符串字段转为数字排序或比大小
2022/06/14 MySQL