Python数据类型之String字符串实例详解


Posted in Python onMay 08, 2019

本文实例讲述了Python数据类型之String字符串。分享给大家供大家参考,具体如下:

String(字符串)

1、概述

字符串是以单引号或双引号括起来的任意文本,比如"abc",‘xy'等等,请注意‘'或者""本身只是一种表示方式,并不是字符串的一部分。

a.若字符串内部包含单引号又包含双引号怎么办?

print('I\'m \"ok\"')

表示的字符串内容是:

I'm "ok"

注意:转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也需要转义,所以\\表示的字符就是\等等

>>>print('I\'m ok.')
I'm ok.
>>>print('I\'m learning\n python.')
I'm leanring
Python.
>>> print('\\\n\\')
\
\

但是,如果字符串里面很多字符串需要转义,就需要添加很多,为了简化,python还允许用r""(或者R"")表示内部的字符串默认不转义。

>>> print('\\\t\\')
\  \
>>>print(r'\\\t\\')
\\\t\\

如果字符串内部很多换行,用\n写在一行里不好阅读,为了简化,python允许用"'…"'的格式表示多行内容:

>>> print('''line1
  line2
  line3''')
line1
line2
line3

2.创建字符串

str1 = "hello world"
str2 = 'you are good'

3.字符串运算

3.1字符串连接

3.1.1 使用加号进行连接

#字符串的连接,通过"+"进行连接
s1 = 'welcome '
s2 = 'to guangzhou'
print(s1 + s2)

输出:

welcome to guangzhou

注意:字符串 + 数字,这样会报错,不同类型的不能相加

3.1.2 使用","进行连接【tuple类型】

s1 = 'hello'
s2 = 'world'
print(s1, s2)
#使用","连接的时候,在","的位置会产生一个空格

输出:

hello world

3.1.3 使用%格式化连接

s1 = 'hello'
s2 = 'world'
print("%s %s"%(s1, s2))

输出:

hello world

3.1.4 使用join函数进行连接

s1 = ['hello', 'world']
print("".join(s1))
print("*".join(s1))

输出:

helloworld
hello*world

注意:"".join()函数只需要传递一个参数【字符串、列表、元组、字典(输出无序)、集合(输出无序),其中的元素应该是字符串类型】。

3.2 重复输出字符串

#重复输出字符串,通过乘法的方式实现
s3 = 'good'
print(s3 * 3)

输出:

goodgoodgood

3.3 获取字符串中的字符

#通过索引的方式实现
#索引:给一个字符串中的字符从0开始编号,也称为下标
#索引的取值范围:[0,len(str)-1]
#访问方式: 变量名称[索引]
str3 = 'good'
print(str3[0])
#索引值还可以从-1开始,-1代表倒数第一个字符
print(str3[-1])

输出:

g
d

3.3 截取字符串

# 通过下标截取字符串
str1 = "hello world"
print(str1[3:6])
#注意:截取字符串的范围是str[start : end] 它是一个前闭后开的区间[start,end)
#如果n的值超过了字符串的最大长度,则仍然截取原下标的长度
#从开头截取到指定索引之前[0,5)
print(str1[:5])
#从指定截取到结尾[4,len(str1))
print(str1[4:])
#注意在使用str[start : end]来截取字符串的时候,若start不写默认从第一个字符开始
#若end不写,则默认到最后一个字符结束。取头去尾。
print("012345"[1:-1])

输出:

lo
hello
o world
1234

3.5 判断是否包含指定字符

#判断字符串中是否包含某指定字符串
str4 = "you are a good boy"
print("good" in str4)
#若包含有则返回True否则为False

输出:

True

3.6 格式化输出

#通过%来改变后面的字母或者是符号的含义,%被称为占位符
# %s:格式化字符串
# %d:格式化整数
# %f:格式化浮点数,可指定小数点后的精度
age = 18
name = "丽丽"
weight = 45.5
print("my name is %s , I am %d year old and my weight is %.2f kg"%(name, age, weight))
#注意:%.nf表示精确到小数点后n位,会四舍五入

输出:

my name is 丽丽 , I am 18 year old and my weight is 45.50 kg

4.关于字符串常用函数

4.1 eval(str)

功能:将字符串str当成有效的表达式来求值并返回计算结果。

可以把list,tuple,dict和string相互转化

>>>num1 = eval('123')
>>>print(num1)
123
>>>num2 = eval("[1, 2, 3]")
>>>print(num2)
[1, 2, 3]
>>> num3 = eval("12-3")
>>> print(num3)
9

4.2 len(str)

功能:返回当前字符串的长度(字符的个数)

>>> len("you are good")
12

4.3 str.lower()

功能:返回一个把字符串中的大写字母转换为小写字母 的字符串

>>> str = "Hello World"
>>> print(str.lower())
hello world

注意:此方法不改变原本的字符

4.4 str.upper()

功能:返回一个把字符串中的小写字母转换为大写字母的字符串

>>> str = "Hello World"
>>> print(str.upper())
HELLO WORLD

4.5 str.swapcase()

功能:返回一个把字符串中的大写字母转为小写字母,小写字母转换为大写字母的字符串

>>> str = "Hello World"
>>> print(str.swapcase())
hELLO wORLD

4.6 str.capitalize()

返回一个首字母大写,其他小写的字符串

>>> str = "Hello World"
>>> print(str.capitalize())
Hello world

4.7 str.title()

返回一个每个单词首字母大写的字符串

>>> str = "Hello World"
>>> print(str.title())
Hello World

4.8 str.center(width[, fillchar])

功能:返回一个指定宽度的居中字符串,fillchar为填充的字符串,默认使用空格

>>> str = "Hello World"
>>> print(str.center(50,"*"))
*******************Hello World********************

4.9 str.ljust(width[, fillchar])

功能:返回一个指定宽度的左对齐字符串,fillchar为填充字符。默认使用空格填充

>>> str = "Hello World"
>>> print(str.ljust(50,"*"))
Hello World***************************************

4.10 str.rjust(width[, fillchar])

功能:返回一个指定宽度右对齐字符串,fillchar为填充字符,默认使用空格填充

>>> str = "Hello World"
>>> print(str.rjust(50,"*"))
***************************************Hello World

4.11 str.zfill(width)

功能:返回一个长度为width字符串,原字符串右对齐,前面补0

>>> str = "Hello World"
>>> print(str.zfill(50))
000000000000000000000000000000000000000Hello World

4.12 str.count(str [,start][, end])

功能:返回字符串中str出现的次数,可以指定一个范围,若不指定则默认从头到尾,匹配的时候是区分大小写的。

>>> str = "Hello World"
>>> print(str.count("hello", 0 , 10))
0

4.13 str.find(str1[, start][, end])

功能:从左到右检测str1字符串是否包含在字符串中,可以指定范围,默认从头到尾。

返回的是第一次出现的开始的下标,若未查询到,则返回-1

>>> str = "Hello World"
>>> str1 = "llo"
>>> print(str.find(str1, 0 , 10))
2

4.14 str.rfind(str1[, start][, end])

功能:类似于str.find(),不过是从右边开始查找

>>> str = "Hello World"
>>> str1 = "llo"
>>> print(str.rfind(str1, 0 , 10))
2

4.15 str.index(str1[, start = 0] ,[ end = len(str)])

功能:类似于find(),与find() 不同的是,如果str1不存在的时候会报一个异常

>>> str2 = "Hello World"
>>> str1 = "hello"
>>> print(str2.index(str1, 0 , 10))
ValueError: substring not found

4.16 str.lstrip()

功能:截掉字符串左侧指定的字符串,默认为空格

>>> str = '**** you are very good'
>>> print(str.lstrip())
>>> print(str.lstrip())
**** you are very good
>>> print(str.lstrip("*"))
 you are very good

4.17 str.rstrip()

功能:截掉字符串右侧指定的字符串,默认为空格

>>> str = '**** you are good****'
>>> print(str.rstrip())
**** you are good****
>>> print(str.rstrip("*"))
**** you are good
str1 = "*nih*a*o*"
print(str1.strip('*'))

输出:

nih*a*o

4.18 string.split(str="", num=string.count(str))

功能:以 str 为分隔符切片 string,如果 num有指定值,则仅分隔 num 个子字符串
str ? 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。 num ? 分割次数

>>> str1 = "hello you are good"
>>> str1.split()
['hello', 'you', 'are', 'good']
>>> str1.split(" ",2)
['hello', 'you', 'are good ']

4.19 str1.splitlines([keepends])

功能:字符串会按照行(‘\r','\r\n','\n')进行分割,返回一个包含各行作为元素的列表,如果参数keepends的值为False,不包含换行符,如果为True,则保留换行符。参数keepends默认为False。

str2 = '''how are
you ?
i am
fine
!
'''
list2 = str2.splitlines()
print(list2)

输出:

['how are', 'you ?', 'i am', 'fine', '!']

str2 = '''how are
you ?
i am
fine
!
'''
list2 = str2.splitlines(keepends=True)
print(list2)

输出:

['how are\n', 'you ?\n', 'i am\n', 'fine\n', '!\n']

4.20 str1.join(seq)

功能:以指定字符串作为分隔符,将seq中的所有元素合并成为一个新的字符串。

list2 = ['you', 'are', 'very', 'great', '!']
str3 = ' '.join(list2)
print(str3)

输出:

you are very great !

str1 = "how are you , i am fine thank you"
str3 = "*".join(str1)
print(str3)

输出:

h*o*w* *a*r*e* *y*o*u* *,* *i* *a*m* *f*i*n*e* *t*h*a*n*k* *y*o*u

注意:如果连接的是字符串,则它会把字符串中的每个字符使用指定字符连接。

4.21 获取最大最小字符

max(str):功能: 返回字符串str中最大的字母

str1 = "how are you , i am fine thank you"
print(max(str1))

输出:

y

min(str):功能:返回字符串str中最小字母

str1 = "how are you , i am fine thank you"
print(min(str1))

输出:

' '

注意:比较的是ASCII码值

4.22字符串的替换

str.replace(old , new [, count])

功能:将字符串中的old替换成new,若不指定count,则默认全部替换,若指定count,则替换前count个

str1 = "how are you , i am fine thank you"
str2 = str1.replace("you" ,'me')
print(str2)

输出:

how are me , i am fine thank me

4.23字符串的映射替换

dic = str.maketrans(oldstr, newstr)

str2.translate(dic)

参数一:要转换的字符 参数二:目标字符

str5 = ""
dic = str5.maketrans("ac", "21")
# a--2  c--1
str7 = "how are you ,u ewe c "
print(str7.translate(dic))

输出:

how  2re you  ,u ewe 1

注意:很少用。

4.24 判断字符串的开头结尾

str.startswith(str1, start=0, end=len(str))

功能:在给定的范围内判断字符串是否以给定的字符串开头,如果没有指定范围,默认整个字符串。

str1 = "aaa bbb ccc deee"
print(str1.startswith("aa"))
str1 = "aaa bbb ccc deee"
print(str1.startswith("aa", 3, 9))

输出:

True
False

str.endswith(str, start=0, end=len(str))

功能:在给定的范围内判断字符串是否以指定的字符串结尾,若没有指定范围,默认为整个字符串。

str1 = "aaa bbb ccc deee"
print(str1.endswith("deee"))
str1 = "aaa bbb ccc deee"
print(str1.endswith("e", 3 ,9))

输出:

True
False

4.25 编码与解码

str.encode(encoding="utf-8", errors="scrict")

功能:字符串的编码,若不指定encoding则默认选择utf-8。

str1 = "你好吗?"
data = str1.encode()
print(data)
print(type(data))

输出:

b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f'
<class 'bytes'>

str.decode(encoding="utf-8")

"hello".encode("utf-8").decode()

功能:对字符进行解码,若不指定编码格式,则默认选择utf-8

str1 = "你好吗?"
data = str1.encode()
print(data)
print(type(data))
data2 = data.decode()
print(data2)
print(type(data2))

输出:

b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f'
<class 'bytes'>
你好吗?
<class 'str'>

注意:解码时的编码格式要与编码时的保持一致

拓展:errors = ignore 的时候,忽略错误

4.26 判断是否为字母或数字

str.isalpha()

功能:判断字符串至少有一个字符,并且所有的字符都是字母(或者包含汉字),若为真则返回True,否则返回False

str8 = "hello ni hao "
print(str8.isalpha())
str9 = "你好"
print(str9.isalpha())

输出:

False
True

str.isalnum()

功能:判断一个字符串至少有一个字符,并且所有的字符都是字母或数字(或者包含汉字)则返回True否则返回False

str9 = '1234你好'
str10 = "sc22xdcd"
str11 = "ss1 2dd"
print(str9.isalnum())
print(str10.isalpha())
print(str11.isalnum())

输出:

True
True
False

4.27 判断大小写

str.isupper()

功能:若字符串中包含至少一个字母的字符,并且这些字母都是大写,则返回True,否则返回False

str10 = "AA2221 你111"
print(str10.isupper())
str10 = "AAaaa"
print(str10.isupper())

输出:

True
False

str.islower()

功能:若字符串中包含至少一个字母的字符,并且这所有的字母都是小写,则返回True,否则返回False。

str10 = "aa2221 你111"
print(str10.islower())

输出:

True

4.28 判断是否包含特殊字符

①、str.istitle()

功能:如果一个字符串是标题化的则返回True,否则返回False

【标题化】每个首字母大写。

str1 = "Hello World"
print(str1.istitle())

输出:

True

②、str.isdigit()

功能:判断字符是否全为数字。

isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节)
False: 汉字数字, ,罗马数字
Error: 无

print("123".isdigit())
print("123a".isdigit())

输出:

True
Fals

③、str.isnumeric()

功能:若字符串中只包含数字字符,则返回True,否则返回False。

isnumeric()
True: Unicode数字,全角数字(双字节),汉字数字
False: 罗马数字,
Error: byte数字(单字节)

print("123一".isnumeric())
print("123a".isnumeric())

输出:

True
False

④、str.isdecimal()

功能:检查字符串是否只包含十进制字符【0,9】,如果是返回True,否则返回False。

isdecimal()
True: Unicode数字,,全角数字(双字节),
False: 罗马数字,汉字数字
Error: byte数字(单字节)

print("123".isdecimal())
print("123z".isdecimal())

输出:

True
False

⑤、str.isspace()

功能:如果字符串只包含空格,则返回True,否则返回False。

print(" ".isspace())
print("\t".isspace())
print("\n".isspace())
print("\r".isspace())
print(" qq".isspace())

输出:

True
True
True
True
False

4.29 ASCII码转换

①、ord(str)

功能:获取字符串的整数表示 ASCII码值。

print(ord("A"))
print(ord("你"))

输出:

65
20320

②、chr(str)

功能:把编码转成对应的字符。

print(chr(68))
print(chr(20190))

输出:

D

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python合并多个装饰器小技巧
Apr 28 Python
Python中MySQLdb和torndb模块对MySQL的断连问题处理
Nov 09 Python
Python cookbook(字符串与文本)在字符串的开头或结尾处进行文本匹配操作
Apr 20 Python
python列表每个元素同增同减和列表元素去空格的实例
Jul 20 Python
python的mysql数据库建立表与插入数据操作示例
Sep 30 Python
从numpy数组中取出满足条件的元素示例
Nov 26 Python
python中的selenium安装的步骤(浏览器自动化测试框架)
Mar 17 Python
django 实现手动存储文件到model的FileField
Mar 30 Python
jupyter notebook运行命令显示[*](解决办法)
May 18 Python
OpenCV+Python3.5 简易手势识别的实现
Dec 21 Python
python爬取豆瓣电影排行榜(requests)的示例代码
Feb 18 Python
Python读取文件夹下的所有文件实例代码
Apr 02 Python
Python数据类型之List列表实例详解
May 08 #Python
Python3使用TCP编写一个简易的文件下载器功能
May 08 #Python
详解Python的三种可变参数
May 08 #Python
Python数据类型之Tuple元组实例详解
May 08 #Python
基于腾讯云服务器部署微信小程序后台服务(Python+Django)
May 08 #Python
python中正则表达式与模式匹配
May 07 #Python
详解Python3网络爬虫(二):利用urllib.urlopen向有道翻译发送数据获得翻译结果
May 07 #Python
You might like
PHP 日期加减的类,很不错
2009/10/10 PHP
php循环检测目录是否存在并创建(循环创建目录)
2011/01/06 PHP
php 数组使用详解 推荐
2011/06/02 PHP
PHP imagegrabscreen和imagegrabwindow(截取网站缩略图)的实例代码
2013/11/07 PHP
php生成不重复随机数、数组的4种方法分享
2015/03/30 PHP
php使用Jpgraph绘制饼状图的方法
2015/06/10 PHP
PHP递归遍历多维数组实现无限分类的方法
2016/05/06 PHP
简单谈谈 php 文件锁
2017/02/19 PHP
PHP高精确度运算BC函数库实例详解
2017/08/15 PHP
sina的lightbox效果。
2007/01/09 Javascript
javascript或asp实现的判断身份证号码是否正确两种验证方法
2009/11/26 Javascript
在Google 地图上实现做的标记相连接
2015/01/05 Javascript
JSON遍历方式实例总结
2015/12/07 Javascript
浅析jQuery 遍历函数,javascript中的each遍历
2016/05/25 Javascript
mongoose中利用populate处理嵌套的方法
2017/05/26 Javascript
Nuxt.js实战详解
2018/01/18 Javascript
vue element-ui table组件动态生成表头和数据并修改单元格格式 父子组件通信
2019/08/15 Javascript
vue之a-table中实现清空选中的数据
2019/11/07 Javascript
React实现全选功能
2020/08/25 Javascript
[02:15]你好,这就是DOTA!
2015/08/05 DOTA
浅谈Python中chr、unichr、ord字符函数之间的对比
2016/06/16 Python
Python 12306抢火车票脚本
2018/02/07 Python
python监控进程脚本
2018/04/12 Python
解决django 新增加用户信息出现错误的问题
2019/07/28 Python
Python如何调用外部系统命令
2019/08/07 Python
python 读取、写入txt文件的示例
2020/09/27 Python
python实现excel公式格式化的示例代码
2020/12/23 Python
美国时尚配饰品牌:Dooney & Bourke
2017/11/14 全球购物
法国二手手袋、手表和奢侈珠宝购物网站:Collector Square
2018/07/05 全球购物
高校学生干部的自我评价分享
2013/11/04 职场文书
汽车专业毕业生推荐信
2013/11/12 职场文书
高级护理专业毕业生推荐信
2013/12/25 职场文书
四查四看自我剖析材料
2014/09/19 职场文书
银行授权委托书格式
2014/10/10 职场文书
基于angular实现树形二级表格
2021/10/16 Javascript
python程序的组织结构详解
2021/12/06 Python