Python入门教程2. 字符串基本操作【运算、格式化输出、常用函数】 <font color=red>原创</font>
作者:chenge 发布时间:2021-08-21 17:17:21
标签:Python,字符串,格式化,常用函数
前面简单介绍了Python基本运算,这里再来简单讲述一下Python字符串相关操作
1. 字符串表示方法
>>> "www.jb51.net" #字符串使用单引号(')或双引号(")表示
'www.jb51.net'
>>> 'www.jb51.net'
'www.jb51.net'
>>> "www."+"jb51"+".net" #字符串可以用“+”号连接
'www.jb51.net'
>>> "#"*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列表有重复元素时,可以有以下几种方式进行删除觉得不错的话,赶紧学起来用用吧 !
- 视频观看视频函数的参数定义函数时,我们把参数的名字和位置确定下来,函数的接口定义就完成了。参数在函数名后的括号内指定。您可以根据需要添加任意
- Python3视频转字符动画,具体代码如下所示:# -*- coding:utf-8 -*-import jsonimport osimpo
- 前言在前边的几篇文章中已经基本分享完了编译器前端的一些工作,后边的几篇主要是关于编译器对抽象语法树进行分析和重构,然后完成一系列的优化,其中
- 一、 操作数据库(mysql)的工具1.1命令行工具1.2navicat界面化工具1.3phpAdmin界面化工具一般情况下安装phpstu
- 一行拆分成多行1.根据某一列拆分效果:代码:if __name__ == '__main__':
- 本文实例讲述了php基于curl实现随机ip地址抓取内容的方法。分享给大家供大家参考,具体如下:使用php curl 我们可以模仿用户行为,
- 这方面我还是一个freshman,不过看了一些文章,经过一些实践后也算是有了一些想法。希望如果有这方面的前辈路过的话,能不吝指教。首先,作为
- Linux环境MySQL服务器级优化讲解 摘要:本节简单介绍了如何在服务器级优化数据库的性能
- 1.InnoDB的锁定机制InnoDB存储引擎支持行级锁,支持事务处理,事务是有一组SQL语句组成的逻辑处理单元,他的ACID特性如下:原子
- 1.列表list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目。列表中的项目。列表中的项目应该包括在方括号中,这样py
- 在使用Python处理数据时,经常需要对数据筛选。这是在对时间筛选时,判断两列时间是否相差一年,如果是,则返回符合条件的所有列。data原始
- llama Index是什么《零开始带你入门人工智能系列》第一篇:还用什么chatpdf,让llama Index 帮你训练pdf。Llam
- 一、浏览器允许每个域名所包含的 cookie 数:Microsoft 指出 Internet Explorer 8 增加 cookie 限制
- 本博客实现将自己训练保存的ckpt模型转换为pb文件,该方法适用于任何ckpt模型,当然你需要确定ckp
- 该计算器功能:1.校验:小数点,重复计算,以及大量更符合用户体验的操作。2.能够从键盘输入。效果图:html代码:<!DOCTYPE
- 随便在网上找了找,感觉都是讲半天讲不清楚,这里写一下。def generator(): while True: &
- 问题描述:在pyhton脚本中logging.info("hello world")希望输出'hello wor
- 这篇文章主要介绍了python代码如何实现余弦相似性计算,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 在PyTorch中可以方便的验证SoftMax交叉熵损失和对输入梯度的计算关于softmax_cross_entropy求导的过程,可以参考