写给小白的Python之004:数据类型之字符串

导读:

1.字符串

2.转义字符

3.字符串的运算

4.字符串的索引

5.字符串的切片

6.字符串的常用操作

 

字符串是Python中很重要的数据类型。

一、字符串

1. 如何表示字符串

单引号、双引号、三引号。

>>> 'hello'
'hello'

>>> "hello"
'hello'

>>>''' Tom said:"I'm Tom" '''
'Tom said:"I'm Tom" '

2. 1和 '1' 是有区别的

>>> type(1)  # 1

<class 'int'>

>>> type('1')  # '1'

<class 'str'>

注:type()可查看数据的类型。int表示整型。str表示字符串。

3. 引号的包裹问题

相同的引号不能互相包裹,只能是不同引号间包裹。

>>> "let's go"

"let's go"

>>> 'let's go'

  File "<stdin>", line 1

    'let's go'

         ^

SyntaxError: invalid syntax

>>> 'let"s go'

'let"s go'

可以使用转义字符:不推荐使用

>>> 'let\'s go'   
"let's go"

4. 代码换行

Python的IDLE中推荐一行输入79个字符,那怎样使代码换行呢?

>>> "hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world"

'hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world'

使用三引号 '''或者 """ ,使代码换行

>>> '''

... hello world

... hello world

... hello world

... '''

'\nhello world\nhello world\nhello world\n'

使用转义字符 \ ,使代码换行

>>> 'hello\
... world'
'helloworld'

5. 输出结果换行

引号内使用换行符,并不能使输出结果换行:

>>> """hello world\nhello world\nhello world"""
'hello world\nhello world\nhello world'

使用 print函数,可以使换行符起作用

>>> print("hello world\nhello world\nhello world")
hello world
hello world
hello world

 

二、转义字符

当我们想要输出一个特殊的字符时,就需要使用转义字符。

特殊的字符:
1)无法“看见”的字符
2)与语言本身语法有冲突的字符

\n 换行,在控制台输出一个 换行符
\' 单引号
\"双引号
\t 横向制表符,在控制台输出一个 制表符,协助在输出文本时 垂直方向 保持对齐。制表符 的功能是在不使用表格的情况下在 垂直方向 按列对齐文本、。
\r 回车
\\反斜杠符号 

对特殊字符进行转义:

'hello world'
>>> print('hello \n world')
hello
world
>>> print('hello \\n world')
hello \n world
>>> print('hello \
... \n world')
hello
world

路径的输出:

>>> print('c:\\program\\python')
c:\program\python
>>> print(r'c:\program\python')
c:\program\python

如果你不想让反斜杠发生转义,可以在字符串前面添加一个r,表示原始字符串:

>>> r'c:windows'
'c:windows'
>>> r'c:\windows'
'c:\\windows'
>>> R'c:\windows'
'c:\\windows'
>>> r'c:\\windows'
'c:\\\\windows'

>>> print(r'let\'s go')
let\'s go

 

 三、字符串的运算

" + "可以连接字符串:

>>> a='hello'
>>>b='world'
>>>a+b
'helloworld'
>>>'%s'%( a+b)
'helloworld'

" *数字 "表示复制字符串的次数:

>>> 'hello '*3
'hello hello hello '

字符串不可以*字符串:

>>> 'hello'*'hello'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'

 

四、字符串的索引

python中下标从 0 开始

>>> 'hello world'[0]
'h'
>>> 'hello world'[3]
'l'
# 索引为负数,表示从字符串右边开始数。
>>> 'hello world'[-3]
'r'
# 索引超出字符串总长度,会报错
>>>"Hello World"[15]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

字符串长度:

aStr='abcdefABCDEF'
print(len(aStr))
结果为:12

print(aStr[len(aStr)-1])
结果为:F

注:len()可统计字符串的长度。

注:没有单独的字符类型,一个字符就是长度为1的字符串。

五、字符串的切片

切片,应该怎样理解呢。如果把字符串比作一块夹心饼干,小时候的你可能会把饼干掰开,然后只吃中间的夹心。这个时候我们就说你对饼干进行了一次切片。当然你也可以把它比作切片面包,随便你怎样,只要有助于你理解切片即可。如果你还是不能够想象到切片是怎样一回事,那么就接着往下看吧,结合实例,相信你一定能够理解。

题外话:事实上,我比较喜欢用很少的文字,更多的代码来讲解知识,我认为这有助于激发你的理解能力,当然如果这样让你无法更好的吸收我所讲的知识,你可以私信我,也许我会改变我的讲解方法。

好了,我们来看字符串的切片吧。

切片的语法:

str[起始:结束:步长]

注意:
1.选取的区间属于左闭右开型,即从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身)。
2.从头开始,开始索引 数字可以省略,冒号不能省略。
3.到末尾结束,结束索引 数字可以省略,冒号不能省略。
4.步长默认为 1,如果连续切片,数字和冒号都可以省略。

Python字符串不能被改变。向一个索引位置赋值,比如 word[0] = 'm' 会导致错误。
[n:m],包括[n]不包括[m]

>>> 'hello world'[0:5]
'hello'
>>> 'hello world'[0:-1]
'hello worl'
>>> 'hello world'[-3:-1]
'rl'

[n:m]即使m远超字符串长度,Python也会忽略:

>>> 'hello world'[6:11]
'world'
>>> 'hello world'[6:20]
'world'

[n:]表示截取从第n个字符截取到最后:

>>> 'hello world'[6:]
'world'

[n:m],n在m右边时,什么都截取不到:

>>> 'hello world'[6:0]
''
>>> 'hello world'[6:-0]
''
>>> 'hello world'[6:3]
''
>>> 'hello world'[-3:0]
''
>>> 'hello world'[-3:-5]
''

步长:

>>> a = "abcdef"
# 省略起始位置,相当于起始位置为0 >>> a[:3] 'abc' >>> a[::2] 'ace' >>> a[5:1:2] '' >>> a[1:5:2] 'bd' >>> a[::-2] 'fdb' >>> a[5:1:-2] 'fd'

长字符串的截取:

>>> 'hello python java c# javascript php ruby'[6:]
'python java c# javascript php ruby'
>>> 'hello python java c# javascript php ruby'[:-4]
'hello python java c# javascript php '
等价于:
>>> 'hello python java c# javascript php ruby'[0:-4]
'hello python java c# javascript php '
截取ruby:
>>> 'hello python java c# javascript php ruby'[-4:]
'ruby'

 

六、字符串的常用操作

字符串的方法有如下(但不限于)这些:

1.判断类型 - 9个

2.查找和替换 - 7个

3.大小写替换 - 5个

4.文本对齐 - 3个

 

5.去除空白字符 - 3个

 

6.拆分和连接 - 5个

 

 实例:

如有字符串string = 'hello world itcast and itcastcpp',以下是常见的操作。

<1>find

检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1。

mystr.find(str, start=0, end=len(string))

 

<2>index

跟find()方法一样,只不过如果str不在 string中会报一个异常。

string.index(str, start=0, end=len(string))

<3>count

返回 str在start和end之间 在 mystr里面出现的次数。

mystr.count(str, start=0, end=len(string))

 

<4>replace

把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次。

string.replace(old_str, new_str,  num=string.count(old_str))

 

<5>split

以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit+1 个子字符串。

string.split(str=" ", maxsplit)    

 

<6>capitalize

把字符串的第一个字符大写。

string.capitalize()

 

<7>title

把字符串的每个单词首字母大写。

mystr.title()

>>> a = "hello itcast"

>>> a.title()

'Hello Itcast'

<8>startswith

检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False。

string.startswith(obj)

 

<9>endswith

检查字符串是否以obj结束,如果是返回True,否则返回 False。

mystr.endswith(obj)

 

<10>lower

转换 string 中所有大写字符为小写。

mystr.lower()

 

<11>upper

转换 string 中的小写字母为大写。

string.upper()

 

<12>ljust

返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串。

mystr.ljust(width)

 

<13>rjust

返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。

mystr.rjust(width)

 

<14>center

返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。

mystr.center(width)   

 

<15>lstrip

删除 string 左边的空白字符。

string.lstrip()

 

<16>rstrip

删除 string 字符串末尾的空白字符。

mystr.rstrip()

 

<17>strip

删除string字符串两端的空白字符。

mystr.strip()

>>> a = "\n\t itcast \t\n"

>>> a.strip()

'itcast'

<18>rfind

类似于 find()函数,不过是从右边开始查找。

mystr.rfind(str, start=0,end=len(string) )

 

<19>rindex

类似于 index(),不过是从右边开始。

mystr.rindex( str, start=0,end=len(string))

 

<20>partition

把string以str分割成三部分,str前,str和str后。

string.partition(str)

 

<21>rpartition

类似于 partition()函数,不过是从右边开始。

mystr.rpartition(str)

 

<22>splitlines

按照行分隔,返回一个包含各行作为元素的列表。

mystr.splitlines()  

 

<23>isalpha

如果 string 所有字符都是字母 则返回 True,否则返回 False。

mystr.isalpha()  

 

<24>isdigit

如果 string 只包含数字则返回 True 否则返回 False。

mystr.isdigit()

 

<25>isalnum

如果 string 所有字符都是字母或数字则返回 True,否则返回 False。

mystr.isalnum()  

 

<26>isspace

如果 string 中只包含空格,则返回 True,否则返回 False。

mystr.isspace()   

 

<27>join

string 中每个字符后面插入str,构造出一个新的字符串。

mystr.join(str)

 

 

练习题:字符串切片

现有字符串num_str = "0123456789",请分别对num_str按下列要求操作:
# 1. 截取从 2 ~ 5 位置 的字符串
# 2. 截取从 2 ~ `末尾` 的字符串
# 3. 截取从 `开始` ~ 5 位置 的字符串
# 4. 截取完整的字符串
# 5. 从开始位置,每隔一个字符截取字符串
# 6. 从索引 1 开始,每隔一个取一个
# 7. 截取从 2 ~ `末尾 - 1` 的字符串
# 8. 截取字符串末尾两个字符
# 9. 字符串的逆序

 

posted @ 2018-03-30 22:29  salmond  阅读(345)  评论(0编辑  收藏  举报