100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 【Python第6篇】Python中的数据类型——字符串及常用运算 函数

【Python第6篇】Python中的数据类型——字符串及常用运算 函数

时间:2023-12-11 13:56:17

相关推荐

【Python第6篇】Python中的数据类型——字符串及常用运算 函数

一、字符串的概念

字符串是由字母、符号、数字等组成的一连串字符,一般放在一组单引号或双引号中间。一个字符串的单引号或双引号必须匹配。请看下面的代码示例:

first_name = 'David'last_name = "Smith"print(first_name)# Davidprint(last_name)# Smith

如果字符串较长,而且是多行,则可以将该字符串放在一组符号(''',三个单引号)中间。请看下面的代码示例:

print('''I wandered lonely as a cloudThat floats on high o'er vales and hills,When all at once I saw a crowd,A host of golden daffodils;Beside the lake, beneath the trees,Fluttering and dancing in the breeze.Continuous as the stars that shineAnd twinkle on the Milky Way,They stretched in never-ending lineAlong the margin of a bay:Ten thousand saw I at a glance,Tossing their heads in sprightly dance.The waves beside them danced, but theyOut-did the sparkling waves in glee:A poet could not but be gay,In such a jocund company:I gazed -and gazed -but little thoughtWhat wealth the show to me had brought:For oft, when on my couch I lieIn vacant or in pensive mood,They flash upon that inward eyeWhich is the bliss of solitude;And then my heart with pleasure fills,And dances with the daffodils.——(William Wordsworth,1770-1850)''')

二、字符串的书写方法

1. 字符串内含有引号的书写方法

由于字符串首尾都需要加引号,因此,如果字符串内含有引号,则需要通过下列方法来处理:

(1) 如果字符串内含有单引号,则需要将字符串放在双引号中间。

(2) 如果字符串内含有双引号,则需要将字符串放在单引号中间。

(3)在字符串内的引号前加上转义符\(反斜杠,backslash)。

(4)在字符串引号前加上字母r,r在这里表示raw string,将不转义字符串内任何内容。

请看下面的代码示例:

单双引号转换:

string1 = 'This is the slogan: "Life is short, I use Python!"'print(string1)# 返回:This is the slogan: "Life is short, I use Python!"string2 = "This is the slogan: 'Life is short, I use Python!'"print(string2)# 返回: This is the slogan: 'Life is short, I use Python!'

反斜杠\:

# 如果字符串内含有引号,可以在字符串内的引号前加转义符\string3 = "This is the slogan: \"Life is short, I use Python!\""print(string3)# 返回: This is the slogan: "Life is short, I use Python!"# 注意:'''反斜杠必须加在引号之前,不能加在引号之后,否则程序会报错。比如上面的代码不可以写成 string3 = "This is the slogan: \"Life is short, I use Python!"\" print(string3) 否则系统会提示SyntaxError: unexpected character after line continuation character'''string4 = "This is the backslash\"print(string4)'''上面的语句出错,主要错误提示:SyntaxError: unterminated string literal (detected at line 1)即\"表示将双引号"转义了,那就没有与前面那个双引号"匹配的双引号了。'''string5 = "This is the backslash\""print(string5)# 返回:This is the backslash" # 疑问:为什么后面有个引号?# '''答:所谓转义,就是让这些原本的特殊字符不作为特殊字符使用。所以双引号加斜杠转义的作用是将双引号不作为字符串标志符看待,而作为普通字符看待。所以自然会输出双引号了'''string6 = "This is the backslash\\"print(string6)# 返回: This is the backslash\# 疑问: 第二个\不是把它后面的"给转义了吗?那不就没有与前面那个双引号"匹配的双引号了吗?'''答:第一个斜杠是转义字符,表示后面一个字符作为普通字符看待,所以会输出第二个\'''

字母r:

string7 = r"This is the slogan: \"Life is short, we use Python!\""print(string7)# 返回:This is the slogan: \"Life is short, we use Python!\"string8 = r"This is the backslash\\"print(string8)# 返回: This is the backslash\\

2. 给字符串加下标的方法

我们可以在字符串变量的后面加上[x:y],x,y为整数,称作下标,用来访问字符串。

字符串的下标从0开始,比如string[0]返回字符串string的第一个字符。

(1)string[0:x]:返回第一个下标至第x个下标所包含的字符,我觉得原书应该是写错了。

(2)string[x:y]:返回字符串string的第x个下标至第y-1个下标所包含的字符。

(3)string[x:]:返回字符串string的第x个下标至最后一个下标所包含的字符。

(4)string[-1]:返回字符串string的最后一个字符。

请看下面的代码示例:

name = 'David Smith'print(name[0])# Dprint(name[0:5])# David # 疑问:为什么不是Davi?不是返回第一个下标到第4个下标的字符吗?print(name[6:9])# Smiprint(name[6:])# Smithprint(name[-1])# hprint(name[-3:-1])# it -3到-1,就是返回-3和-2,h算作-1的话,-3和-2就是it呀

三、字符串的运算

字符串运算主要涉及两个字符串相加和某个字符串重复n次。

1. string1 + string2: 两个字符串相加。

2. string * n:将string字符串重复n次。

请看下面的代码示例:

first_name = 'David'last_name = 'Smith'name1 = first_name + last_nameprint(name1)# DavidSmithname2 = first_name + ' ' + last_nameprint(name2)# David Smith 注意单引号中间有一个空格print(first_name * 2)# DavidDavidprint((first_name + ' ')*2)# David David

四、字符串与数值的互换

我们在处理数据时,需要注意不能把字符串和数值混淆。字符串和数值的互换方法如下:

1. 使用函数str()将数值转换成字符串。

2. 使用函数float()或int()将字符串转换成数值。

请看下面的代码示例:

x = 5# 整数数值print(str(x))# 返回字符串'5'y = '6'# 字符串print(float(y))# 返回浮点数值6.0print(int(y))# 返回整数数值6print(y*x)# 返回字符串'66666'print(float(y)*x)# 返回浮点数值30.0print(int(y)*x)# 返回整数数值30

五、常用字符串函数

1. 长度&大小写相关的函数

请看下面的代码示例:

str1 = 'Life is short'str2 = 'we use python'print(len(str1))# 13 注意:空格也算作一个字符的长度print(str1.lower())# life is shortprint(str2.upper())# WE USE PYTHONprint(str2.capitalize())# We use pythonprint(str2.title())# We Use Pythonstr3 = 'aBcD'print(str3.swapcase())# AbCd

2. 删除空格的函数

本小节介绍删除字符串前后空格的函数。这些函数常用语清洁文本,如下表所示:

请看下面的代码示例:

str1 = ' Life is short 'print(str1.strip())# 'Life is short'print(str1.lstrip())# 'Life is short 'print(str1.rstrip())# ' Life is short'

3. 对字符串进行判断的相关函数

本小节介绍对字符串进行判断的相关函数,如下表所示。这些函数返回布林值(Boolean)True或者False,因此,它们通常与 if 等条件句连用。

请看下面的代码示例:

str1 = 'Life is short'str2= 'Year'print(str1.startwith('L'))# 返回True,注意Python大小写敏感print(str1.endswith('T'))# 返回False,注意Python大小写敏感print(str1.isalnum())# 返回False,因为字符串中含有空格print(str2.isalnum())# 返回Trueprint(str2.isdigit())# 返回Falseprint(str1.islower())# 返回Falseprint(str1.isupper())# 返回Falseprint(str1.istitle())# 返回Falsestr3 = 'Life Is Short'print(str3.istitle())# 返回Truestr4 = ''str5 = ' 'print(str4.isspace())# 返回Falseprint(str5.isspace())# 返回True

参考资料:雷蕾. 基于Python的语料库数据处理[M]. 北京:科学出版社,.25-32.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。