网络编程
位置:首页>> 网络编程>> Python编程>> Python入门教程2. 字符串基本操作【运算、格式化输出、常用函数】 <font color=red>原创</font>

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~

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

0
投稿

猜你喜欢

  • 常见的双倍边距类问题都遇到过,但很少遇到这种有意思的,所以记录一下。这个BUG是发生在Standards模式下(就是包含XHTML或者HTM
  • 前言利用Python docx模块,可以很方便地打开和修改Word 2007及以后的文档。本文简单地介绍了如何使用python修改word文
  • 以下排序算法最终结果都默认为升序排列,实现简单,没有考虑特殊情况,实现仅表达了算法的基本思想。冒泡排序内层循环中相邻的元素被依次比较,内层循
  • 1.尽量不要对列名进行函数处理。而是针对后面的值进行处理例如where col1 = -5的效率比where -col1=5的效率要高因为后
  • 单线程同步使用socket传输数据使用json序列化消息体struct将消息编码为二进制字节串,进行网络传输消息协议// 输入{  
  • 先给大家介绍下python交互模式下输入换行/输入多行命令的方法换行方法 \如:>>> print 'aaa
  • str_replace — 子字符串替换 [str_replace]mixed str_replace ( mixed
  • UPA2008于2008年10月24日在深圳举行,托哥、绿桔应邀主持了一场圆桌会和一场工作坊,以下是圆桌会议《商业价值与用户价值的平衡》的现
  • 一、基本概念Reactive X中有几个核心的概念,先来简单介绍一下。1.1、Observable和Observer(可观察对象和观察者)首
  • 新年新气象,今天就用代码来制作一个 动态鞭炮 ,效果如下所示。动态鞭炮的基本原理是:将一个录制好的鞭炮视频以字符画的形式复现,基本步骤是帧采
  • 一个不错的网页拾色器也叫调色版,请看截图:当想要更多颜色时点击“其它颜色...”此时将调用系统自带的那个颜色选择框:注意:只有把〈scrip
  • 描述tan() 返回x弧度的正弦值。语法以下是 tan() 方法的语法:import mathmath.tan(x)注意:tan()是不能直
  • 案例故事:大部分带彩色屏幕的终端设备,不管是手机,车机,电视等等,都需要涉及图片的显示,作为一名专业的多媒体测试人员,我们需要一堆的规范化标
  • 此BUG最初是在《前端观察》网站刊登,这里再描述一下,代码如下:<style>*{ padding:0; m
  •  无聊的人在无聊的时间做无聊的事打发自己,结果在无聊的事情中发现了IE对内联文字解释的一些疑惑。以下问题在FF2中没发现,而我也只
  • 一、引入这段时间一直在学习Python的东西,以前就听说Python爬虫多厉害,正好现在学到这里,跟着小甲鱼的Python视频写了一个爬虫程
  • SQL Server 2008的独到之处:安装SQL Server 2008的设置和安装也有所改进。配置数据和引擎位已经分开了,所以它使创建
  • iframe的防插与强插(一)中介绍了“市面上”能见到的两种防御被第三方网站iframe的方法,以及相应的变态突破方法。貌似把“受害人”逼上
  • 我是这样来做DIV布局代码的.不知道说的清楚不清楚,凑和看吧我把class分为2种,布局class,风格class,布局class是骨架,风
  • 想要一个这玩意,可是找了网上许多着色器,要么是兼容性成问题,要么是匹配不精确,比如说:1、注释里包含字符串、关键词,类似于:/* xxxx&
手机版 网络编程 asp之家 www.aspxhome.com