[原创]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通过yield实现数组全排列的方法
Mar 18 Python
在Python3中初学者应会的一些基本的提升效率的小技巧
Mar 31 Python
python之Socket网络编程详解
Sep 29 Python
用python与文件进行交互的方法
Mar 01 Python
使用Python机器学习降低静态日志噪声
Sep 29 Python
Python读取txt内容写入xls格式excel中的方法
Oct 11 Python
python面向对象入门教程之从代码复用开始(一)
Dec 11 Python
python 调试冷知识(小结)
Nov 11 Python
pytorch加载自定义网络权重的实现
Jan 07 Python
Python pip install如何修改默认下载路径
Apr 29 Python
Python如何输出百分比
Jul 31 Python
Python使用urlretrieve实现直接远程下载图片的示例代码
Aug 17 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列出mysql表所有行和列的方法
2015/03/13 PHP
Yii2单元测试用法示例
2016/11/12 PHP
基于Laravel实现的用户动态模块开发
2017/09/21 PHP
Javascript玩转继承(三)
2014/05/08 Javascript
Node.js中npm常用命令大全
2016/06/09 Javascript
原生js实现日期计算器功能
2017/02/17 Javascript
JS表单提交验证、input(type=number) 去三角 刷新验证码
2017/06/21 Javascript
JavaScript在控件上添加倒计时功能的实现代码
2017/07/04 Javascript
Angular5升级RxJS到5.5.3报错:EmptyError: no elements in sequence的解决方法
2018/04/09 Javascript
Vue-router 中hash模式和history模式的区别
2018/07/24 Javascript
Vue插件打包与发布的方法示例
2018/08/20 Javascript
Vue文件配置全局变量的实例
2018/09/06 Javascript
详解webpack 热更新优化
2018/09/13 Javascript
JavaScript常用数组操作方法,包含ES6方法
2020/05/10 Javascript
微信小程序vant弹窗组件的实现方式
2020/02/21 Javascript
[01:29:31]VP VS VG Supermajor小组赛胜者组第二轮 BO3第一场 6.2
2018/06/03 DOTA
python使用PyCharm进行远程开发和调试
2017/11/02 Python
Python编程django实现同一个ip十分钟内只能注册一次
2017/11/03 Python
python: 判断tuple、list、dict是否为空的方法
2018/10/22 Python
Python实现将Excel转换成为image的方法
2018/10/23 Python
Python实现使用request模块下载图片demo示例
2019/05/24 Python
Python比较配置文件的方法实例详解
2019/06/06 Python
pandas 对日期类型数据的处理方法详解
2019/08/08 Python
基于YUV 数据格式详解及python实现方式
2019/12/09 Python
python入门之井字棋小游戏
2020/03/05 Python
Python中random模块常用方法的使用教程
2020/10/04 Python
HTML5 UTF-8 中文乱码的解决方法
2013/11/18 HTML / CSS
意大利制造的男鞋和女鞋:SCAROSSO
2018/03/07 全球购物
提高EJB性能都有哪些技巧
2012/03/25 面试题
软件工程师岗位职责
2013/11/16 职场文书
专业销售业务员求职信
2013/11/18 职场文书
八项规定整改方案
2014/02/21 职场文书
承诺书格式范文
2014/06/03 职场文书
庆国庆活动总结
2014/08/28 职场文书
vue选项卡切换的实现案例
2022/04/11 Vue.js
IDEA 2022 Translation 未知错误 翻译文档失败
2022/04/24 Java/Android