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中装饰器的一个妙用
Feb 08 Python
用Python编写一个简单的Lisp解释器的教程
Apr 03 Python
Python实现比较两个列表(list)范围
Jun 12 Python
python批量替换页眉页脚实例代码
Jan 22 Python
Python实现的旋转数组功能算法示例
Feb 23 Python
Python爬取数据保存为Json格式的代码示例
Apr 09 Python
python安装numpy和pandas的方法步骤
May 27 Python
python django 原生sql 获取数据的例子
Aug 14 Python
python网络爬虫 CrawlSpider使用详解
Sep 27 Python
pytorch 改变tensor尺寸的实现
Jan 03 Python
python3.8与pyinstaller冲突问题的快速解决方法
Jan 16 Python
pycharm快捷键汇总
Feb 14 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 STRING 陷阱原理说明
2010/07/24 PHP
PHP的cURL库功能简介 抓取网页、POST数据及其他
2011/04/07 PHP
php实现购物车功能(上)
2020/07/23 PHP
数理公式,也可以这么唯美
2021/03/10 无线电
jquery 设置style:display的方法
2015/01/29 Javascript
jquery图片切换实例分析
2015/04/15 Javascript
实例解析jQuery插件EasyUI最常用的表单验证规则
2015/11/29 Javascript
JavaScript中的Object对象学习教程
2016/05/20 Javascript
基于JS实现省市联动效果代码分享
2016/06/06 Javascript
JavaScript直播评论发弹幕切图功能点集合效果代码
2016/06/26 Javascript
fullPage.js和CSS3实现全屏滚动效果
2017/05/05 Javascript
Angular2里获取(input file)上传文件的内容的方法
2017/09/05 Javascript
webpack 3.X学习之多页面打包的方法
2018/09/04 Javascript
vue-cli 使用vue-bus来全局控制的实例讲解
2018/09/15 Javascript
JavaScript实现简单的图片切换功能(实例代码)
2020/04/10 Javascript
Vue-cli3生成的Vue项目加载Mxgraph方法示例
2020/05/31 Javascript
vue+flask实现视频合成功能(拖拽上传)
2021/03/04 Vue.js
Python实现的tab文件操作类分享
2014/11/20 Python
理解Python中的With语句
2015/02/02 Python
对pandas中to_dict的用法详解
2018/06/05 Python
10分钟教你用Python实现微信自动回复功能
2018/11/28 Python
python绘制评估优化算法性能的测试函数
2019/06/25 Python
简单了解Python3 bytes和str类型的区别和联系
2019/12/19 Python
python实现批量命名照片
2020/06/18 Python
Python headers请求头如何实现快速添加
2020/11/03 Python
Onzie官网:美国时尚瑜伽品牌
2019/08/21 全球购物
个人实用的自我评价范文
2013/11/23 职场文书
教师试用期自我鉴定
2014/02/12 职场文书
业务员自荐信范文
2014/04/20 职场文书
水电站项目建议书
2014/05/12 职场文书
我的中国梦演讲稿1000字
2014/08/19 职场文书
个人务虚会发言材料
2014/10/20 职场文书
2014年法务工作总结
2014/12/11 职场文书
人工作失职检讨书
2015/05/05 职场文书
承诺书应该怎么写?
2019/09/10 职场文书
Golang获取List列表元素的四种方式
2022/04/20 Golang