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中工作日类库Busines Holiday的介绍与使用
Jul 06 Python
详解Python开发中如何使用Hook技巧
Nov 01 Python
Python通过命令开启http.server服务器的方法
Nov 04 Python
分析经典Python开发工程师面试题
Apr 08 Python
在Django下创建项目以及设置settings.py教程
Dec 03 Python
torch 中各种图像格式转换的实现方法
Dec 26 Python
keras实现theano和tensorflow训练的模型相互转换
Jun 19 Python
python中如何设置代码自动提示
Jul 15 Python
Python使用Selenium模拟浏览器自动操作功能
Sep 08 Python
selenium学习教程之定位以及切换frame(iframe)
Jan 04 Python
Python使用OpenCV和K-Means聚类对毕业照进行图像分割
Jun 11 Python
Python学习之迭代器详解
Apr 01 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
E路文章系统PHP
2006/12/11 PHP
PHP函数之error_reporting(E_ALL ^ E_NOTICE)详细说明
2011/07/01 PHP
php站内搜索关键词变亮的实现方法
2014/12/30 PHP
php递归调用删除数组空值元素的方法
2015/04/28 PHP
jquery cookie插件代码类
2009/05/26 Javascript
javascript DOM编程实例(智播客学习)
2009/11/23 Javascript
读jQuery之十二 删除事件核心方法
2011/07/31 Javascript
javascript使用for循环批量注册的事件不能正确获取索引值的解决方法
2014/12/20 Javascript
如何防止JavaScript自动插入分号
2015/11/05 Javascript
基于AngularJS+HTML+Groovy实现登录功能
2016/02/17 Javascript
浅谈js图片前端预览之filereader和window.URL.createObjectURL
2016/06/30 Javascript
购物车前端开发(jQuery和bootstrap3)
2016/08/27 Javascript
javascript-解决mongoose数据查询的异步操作
2016/12/22 Javascript
AngularJS使用ng-app自动加载bootstrap框架问题分析
2017/01/04 Javascript
12306 刷票脚本及稳固刷票脚本(防挂)
2017/01/04 Javascript
jQuery.ajax向后台传递数组问题的解决方法
2017/05/12 jQuery
vue axios用法教程详解
2017/07/23 Javascript
React-Native之定时器Timer的实现代码
2017/10/04 Javascript
vue如何引入sass全局变量
2018/06/28 Javascript
js代码实现轮播图
2020/05/04 Javascript
[04:11]2014DOTA2国际邀请赛 CIS遗憾出局梦想不灭
2014/07/09 DOTA
[16:21]教你分分钟做大人:圣堂刺客
2014/12/03 DOTA
python搭建服务器实现两个Android客户端间收发消息
2018/04/12 Python
Win10环境python3.7安装dlib模块趟过的坑
2019/08/01 Python
PyTorch的Optimizer训练工具的实现
2019/08/18 Python
Python中的四种交换数值的方法解析
2019/11/18 Python
WxPython实现无边框界面
2019/11/18 Python
Python numpy多维数组实现原理详解
2020/03/10 Python
Python 基于jwt实现认证机制流程解析
2020/06/22 Python
分享PyCharm最新激活码(真永久激活方法)不用每月找安装参数或最新激活码了
2020/12/27 Python
Meli Melo官网:名媛们钟爱的英国奢侈手包品牌
2017/04/17 全球购物
C语言变量的命名规则都有哪些
2013/12/27 面试题
专科毕业生就业推荐信
2013/11/01 职场文书
化学教育专业自荐信
2014/07/04 职场文书
上课睡觉检讨书300字
2014/11/18 职场文书
小学运动会加油稿
2015/07/22 职场文书