您现在的位置是:亿华云 > 热点

Python基本数据类型之字符串

亿华云2025-10-04 00:44:30【热点】5人已围观

简介str字符串)1.字符串是 Python 中最常用的数据类型。我们可以使用,"", , """ """这四种方式来定义字符串;a =xb ="y"c =xxxd ="""yyy"""print(a,b

str(字符串)

1.字符串是基本 Python 中最常用的数据类型。我们可以使用,数据"", , """ """这四种方式来定义字符串;a =xb ="y"c =xxxd ="""yyy"""print(a,b,c,d)#输出:x y xxx yyy

2.字符串是不可变的,字符串一旦定义就不能改变;

Python基本数据类型之字符串

string=worldstring=hello world

3.字符串的类型转义;

Python基本数据类型之字符串

\:续行符;\e:转义;\n:换行;\ \:反斜杠符号;\ ":单引号;\ ":双引号;\000:空;\v:纵向制表符;\t:横向制表符;\r:回车;\f:换页;\oyy:八进制数,yy代表的符串字符,例如:\o12代表换行;xyy:十六进制数,基本yy代表的数据字符,例如:\x0a代表换行;\other:其它的类型字符以普通格式输出;

4.字符串可以通过索引和循环迭代两种方式来访问;

Python基本数据类型之字符串

# 索引访问str =helloprint(str[1])#输出:e# 循环迭代访问str1 =hellofor item in str1:print(item)#输出:h e l l o

5.字符串的亿华云连接方式

使用 + 号直接连接; string1 =hellostring2 =\tstring3 =worldprint(string1 + string2 + string3)#输出:hello world 使用join方法连接; lst =[1,2,3,4,5]lst_new =.join(lst)print(lst_new)#输出:12345

6.字符串的切割

使用 split(sep=None, maxsplit=num) -> list of strings , 从左向右切割,sep指定分隔符,符串maxsplit指定切割的基本次数, num指定切割多少次,数据如果不设置maxsplit参数,类型那就根据sep切割,符串不限定次数; string1 =1,基本2,3,4,5new_obj1 = string1.split(,)new_obj2 = string1.split(,, maxsplit=1)print(new_obj1)#输出:[1, 2, 3, 4, 5]print(new_obj2)#输出:[1, 2,3,4,5] 使用rsplit方法, rsplit(sep=None, maxsplit=num) -> list of strings,参数设置和split方法类似,不同之处在于,数据 rsplit方法是类型从右向左切割的; string1 =1,2,3,4,5new_obj1 = string1.rsplit(,)new_obj2 = string1.rsplit(,, maxsplit=1)print(new_obj1)#输出:[1, 2, 3, 4, 5]print(new_obj2)#输出:[1,2,3,4, 5] 使用splitlines方法, splitlines([keepends]) -> list of strings, 换行符(\r, \r\n, \n)切割, keepends指是亿华云计算否保留分隔符,True为保留,False不保留; string1 =I love xkd \nI love xkdnew_obj1 = string1.splitlines()new_obj2 = string1.splitlines(True)print(new_obj1)#输出:[I love xkd , I love xkd]print(new_obj2)#输出:[I love xkd \n, I love xkd] 使用partition方法, partition(sep) -> (head, sep, tail), 从左到右切割三段,中间那段为分隔符。如果只需要输出其中一段,可以把其它的段用_下划线代替; string1 =1,2,3,4,5new_obj1, seq, new_obj2 = string1.partition(,)print(new_obj1)#输出:1print(seq)#输出:,print(new_obj2)#输出:2,3,4,5new_obj1, _, _ = string1.partition(,)print(new_obj1)#输出:1

7.字符串对象方法

string=aBcd abcD#初始化一个字符串string 全部转为大写; print(string.upper())#输出:ABCD ABCD 全部转为小写; print(string.lower())#输出:abcd abcd 大写改小写,小写改大写; print(string.swapcase())#输出:AbCD ABCd 所有单词首字母大写; print(string.title())#输出:Abcd Abcd 字符串首字母大写; print(string.capitalize())#输出:Abcd abcd center方法,center(width[, fillchar]) -> str, 将字符串居中,width指定宽度, fillchar指定填充的字符; print(string.center(100,*))输出:

云服务器提供商

很赞哦!(13)