Learning Python Part I 之 字符串
来源:互联网 发布:知乎电影1942精彩片段 编辑:程序博客网 时间:2024/05/16 05:01
字符串——一串有序的字符用来储存或代表文本或者位信息。
- 在Python3.x中,有三种字符串类型: Str 用于 Unicode文本(包括 ASC II); bytes用于二进制数据(包括编码文本); bytearray是bytes的变体,是可变的(mutable)。文件有两种模式:通过Unicode编码的Str文本和bytes表示的二进制数据。
在Python2.x中,unicode 字符串表示Unicode文本,Str字符串处理8位文本和二进制数据。并且bytearray在2.6中也是可用的。常见的文件内容用str表示,但是codecs模块打开Unicode文件并用unicode对象代表内容,处理解码问题。
从功能的角度来讲,字符串能够表示任何可以被编码成文本或字节的信息。其中包括符号和字,这些信息被储存在内存中,可以代表IP地址、Python源码等。字符串也可以用来代表媒体文件和网络传输的原始字节信息,并且以非ASCII码的Unicode文本的形式编码和解码。
Python中的字符串被归类为不可变序列,字符串所包含的字符有从左到右的位置顺序并且一经创建就不能改变。
下表是字符串基本的创建方法与基本操作:
除了这些核心字符串工具外,Python通过标准库模块 re 也支持更加高级的基于模式的字符串处理。和更加高级的文本处理如XML解析等。进一步了解可以查询Python的在线手册。
字符串基础
创建
' '
和 " "
均可以创建字符串,''' '''
或 """ """
用于创建多行字符串。
>>> 'shrubbery', "shrubbery"('shrubbery', 'shrubbery')>>> 'knight"s', "knight's"('knight"s', "knight's")>>> title = "Meaning " 'of' " Life" #python会自动连接字符串>>> title'Meaning of Life'
转义符
举例:
>>> s = 'a\nb\tc'>>> print(s)ab c>>> s'a\nb\tc'>>> s = "s\tp\na\x00m">>> print(s)s pam
抑制转义符
有时候文件目录字符串中可能会包含有转义符的形式,但是此时我们并不需要转义:
>>> myfile = open('C:\new\text.dat', 'w') #其中包含换行符和制表符
我们可以在字符串前加一个r实现:
>>> myfile = open(r'C:\new\text.dat', 'w')
或者用双斜杠:
>>> myfile = open('C:\\new\\text.dat', 'w')
python代码中也可以用反斜杠表示文件路径:
'C:/new/text.dat'
多行字符串
>>> s = """ Always look... on the bright... side of life.""">>> s' Always look\n on the bright\nside of life.'>>> print(s) Always look on the brightside of life.
多行字符串的注释
>>> s = """first #comments here added to string... second #wow... """>>> s = (... "first" #comment here ignored... "second\n" #but newlines not automatic... "end")>>> print(s)firstsecondend
用多行字符串注释代码
X = 1""" #注释这里的代码import osprint(os.getcwd())"""Y = 2
基本操作
>>> len('abc') #字符串的长度3>>> 'abc' + 'def' #连接字符串'abcdef'>>> 'wow~' * 4 #字符串倍增'wow~wow~wow~wow~'>>> str = 'python'>>> for s in str : print(s, end=' ') #遍历字符串... p y t h o n >>>>>> 'p' in str #判断字符是否在字符串中True>>> str[1] #通过索引访问特定位置的字符'y'>>> str[2]'t'
切片
偏移位置示意图:
>>> str = "hey! this is python">>> str[1:5] ,str[1:] ,str[:-1]('ey! ', 'ey! this is python', 'hey! this is pytho')>>> str[:]'hey! this is python'>>> str[::2]'hy hsi yhn'>>> str[1:5:2] #第三个参数可以设置步长,如每两个字符取一个字符'e!'>>> str[::-1] #当步长为非-1 的时候可以翻转字符串'nohtyp si siht !yeh'
字符串转换
>>> num = '12'>>> num + 2 #字符串不能和数字相加Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: must be str, not int>>> int(num) + 2 #将字符串转换为数字14>>> num + str(2) #将数字转换为字符串'122'>>> text = '1.234E-10'>>> float(text) #转换为浮点型1.234e-10>>> ord('s') #s对应的ASCII码115>>> chr(115)'s'>>> int('1101', 2) #将二进制数转换为整数13>>> bin(13) #将整数转换为二进制数'0b1101'
字符串方法
举例:
>>> str = 'i am so handsome'>>> str.split()['i', 'am', 'so', 'handsome']>>> str.title() #返回字符串的标题版本'I Am So Handsome'>>> str.upper() #返回字符串的大写版本'I AM SO HANDSOME'>>> str.lower() #返回字符串的小写版本'i am so handsome'>>> str.swapcase() #返回大小写交换后的版本'I AM SO HANDSOME'>>> s = 'string no 1'>>> s.isalnum() #检查所有字符是否为字母数字False #含有空格,返回false>>> s.isalpha() #检查字符串中是否只有字母False>>> ss = '123456'>>> ss.isalnum()True>>> sss='Python*is*so*cool'>>> sss.split('*')#分割字符串可以传递一个参数['Python', 'is', 'so', 'cool']>>> '-'.join(sss)#指定字符连接多个字符串'P-y-t-h-o-n-*-i-s-*-s-o-*-c-o-o-l'>>> '-'.join(sss.split('*'))'Python-is-so-cool'>>> s = ' asdf'>>> s.strip()#剥离字符串首尾中指定的字符,允许有一个字符串参数'asdf'>>> s' asdf'>>> s = 'www.baidu.com'>>> s.lstrip("wid.")#只对字符串左剥离'baidu.com'>>> s.rstrip("mc.d")#只对字符串右剥离'www.baidu.co'>>> s.rstrip("mcd")'www.baidu.co'>>> s.rstrip(".")'www.baidu.com'>>> s.find("bai")#搜索字符串中指定字符的开始位置4>>> s.find("google")#不存在返回 -1-1>>> s.startswith("www") #检查字符串是否以www开头True>>> s.endswith("com") #检查字符串是否以com结尾True
字符串格式化
字符串格式化的标准格式为
%[(关键字)][符号][宽度][.精度]类型码
- 关键字:字典法中的索引
- 符号:负号( - )为右边补全,正号( + )为左边补全
- 宽度:指输出字符的宽度
- 精度:一般指保留几位小数
- 类型码:格式化字符的类型(整数、浮点数、字符串等)
类型码:
表达式法
>>> res = 'integer: ...%d...%-6d...%6d...%06d' % (1234,1234,1234,1234)>>> res'integer: ...1234...1234 ... 1234...001234'>>> x = 1.23456789>>> '%e | %f | %g' % (x, x, x)'1.234568e+00 | 1.234568 | 1.23457'>>> '%E' % x'1.234568E+00'>>> '%-6.2f | %05.2f | %+06.1f' % (x, x, x)'1.23 | 01.23 | +001.2'
当宽度还不确定时我们可以用 * 替位,并在之后输入
>>> '%f, %.2f,%.*f' % (1/3.0, 1/3.0, 4, 1/3.0)'0.333333, 0.33,0.3333'
通过字典的方法:
>>> reply = """... Greetings...... Hello %(name)s!... Your age is %(age)s... """>>> values = {'name': 'jack', 'age': 40}>>> print(reply % values)Greetings...Hello jack!Your age is 40>>>
format
顺序位置定位:
>>> template = '{0}, {1} and {2}'>>> template.format('spam', 'ham', 'eggs')'spam, ham and eggs'
关键词定位:
>>> template = '{motto}, {pork} and {food}'>>> template.format(motto='spam', pork='ham', food='eggs')'spam, ham and eggs'
混合定位:
>>> template = '{motto}, {0} and {food}'>>> template.format('ham', motto='spam', food='eggs')'spam, ham and eggs'
相关位置定位:
>>> template = '{}, {} and {}'>>> template.format('spam', 'ham', 'eggs')'spam, ham and eggs'
format还支持更对高级的用法:
>>> import sys>>> 'My {map[kind]} runs {sys.platform}'.format(sys = sys,map={'kind' : 'laptop'})'My laptop runs linux'
>>> somelist = list('SPAM')>>> somelist['S', 'P', 'A', 'M']>>> 'first={0[0]}, third={0[2]}'.format(somelist)'first=S, third=A'>>> 'first={0}, last={1}'.format(somelist[0], somelist[-1])'first=S, last=M'>>> parts = somelist[0], somelist[-1], somelist[1:3]>>> 'first={0}, last={1}, middle={2}'.format(*parts)"first=S, last=M, middle=['P', 'A']
format还有更多高级的功能,用到的时候可以查python在线手册
阅读全文
0 0
- Learning Python Part I 之 字符串
- Learning Python Part I 之动态类型
- Learning Python Part I 之 列表
- Learning Python Part I 之 字典
- Learning Python Part I 之 元组
- Learning Python Part I 之 文件
- Learning Python Part I之数字类型(Numeric Types)
- Learning Python :Part I 数据类型和操作
- Learning Python Part II 之 Print
- Learning Python Part II 之 nonlocal语句
- Learning Python Part III 之 模块
- Learning Python Part II 之 迭代和推导式
- Learning Python Part II 之 赋值语句(Assignments)
- Learning Python Part II 之 表达式语句(Expression)
- Learning Python Part II 之 作用域(scope)
- Learning Python Part III 之 Import 是如何工作的
- Learning Python Part III 之 字节代码文件:__pycache__
- Learning Python Part III 之 模块的搜索路径
- 如何在 JS 中嵌入 HTML 代码?
- ST 表 模板
- 不创建系统保留分区
- C/S和B/S 以及初识Tomcat
- POJ 1470 Closest Common Ancestors 离线LCA
- Learning Python Part I 之 字符串
- 自己模拟strcpy库函数写的功能函数my_strcpy实现strcpy的功能,完整代码
- 算法总结五
- 快速排序
- R学习:通过REmap向Echarts中的地图写入数据(运行自带例子)
- 关闭windows的autoplay
- 单例模式的几种实现方式
- CS231n学习笔记--8.Deep Learning Software
- Linux之Shell脚本学习笔记