Python进阶之路---1.5python数据类型-字符串
字符串
*:first-child {
margin-top: 0 !important;
}
body>*:last-child {
margin-bottom: 0 !important;
}
/* BLOCKS
=============================================================================*/
p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}
/* HEADERS
=============================================================================*/
h1, h2, h3, h4, h5, h6 {
margin: 20px 0 10px;
padding: 0;
font-weight: bold;
-webkit-font-smoothing: antialiased;
}
h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
font-size: inherit;
}
h1 {
font-size: 28px;
color: #000;
}
h2 {
font-size: 24px;
border-bottom: 1px solid #ccc;
color: #000;
}
h3 {
font-size: 18px;
}
h4 {
font-size: 16px;
}
h5 {
font-size: 14px;
}
h6 {
color: #777;
font-size: 14px;
}
body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}
a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}
h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}
/* LINKS
=============================================================================*/
a {
color: #4183C4;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* LISTS
=============================================================================*/
ul, ol {
padding-left: 30px;
}
ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}
ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}
dl {
padding: 0;
}
dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}
dl dt:first-child {
padding: 0;
}
dl dt>:first-child {
margin-top: 0px;
}
dl dt>:last-child {
margin-bottom: 0px;
}
dl dd {
margin: 0 0 15px;
padding: 0 15px;
}
dl dd>:first-child {
margin-top: 0px;
}
dl dd>:last-child {
margin-bottom: 0px;
}
/* CODE
=============================================================================*/
pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}
code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}
pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}
pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}
pre code, pre tt {
background-color: transparent;
border: none;
}
kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}
/* QUOTES
=============================================================================*/
blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}
blockquote>:first-child {
margin-top: 0px;
}
blockquote>:last-child {
margin-bottom: 0px;
}
/* HORIZONTAL RULES
=============================================================================*/
hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}
/* TABLES
=============================================================================*/
table th {
font-weight: bold;
}
table th, table td {
border: 1px solid #ccc;
padding: 6px 13px;
}
table tr {
border-top: 1px solid #ccc;
background-color: #fff;
}
table tr:nth-child(2n) {
background-color: #f8f8f8;
}
/* IMAGES
=============================================================================*/
img {
max-width: 100%
}
-->
python字符串与字符编码
字符编码
字符编码
我们已经讲过了,字符串也是一种数据类型,但是,字符串比较特殊的是还有一个编码问题。
因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理。最早的计算机在设计时采用8个比特(bit)作为一个字节(byte),所以,一个字节能表示的最大的整数就是255(二进制11111111=十进制255),如果要表示更大的整数,就必须用更多的字节。比如两个字节可以表示的最大整数是65535,4个字节可以表示的最大整数是4294967295。
由于计算机是美国人发明的,因此,最早只有127个字母被编码到计算机里,也就是大小写英文字母、数字和一些符号,这个编码表被称为ASCII编码,比如大写字母A的编码是65,小写字母z的编码是122。
但是要处理中文显然一个字节是不够的,至少需要两个字节,而且还不能和ASCII编码冲突,所以,中国制定了GB2312编码,用来把中文编进去。
你可以想得到的是,全世界有上百种语言,日本把日文编到Shift_JIS里,韩国把韩文编到Euc-kr里,各国有各国的标准,就会不可避免地出现冲突,结果就是,在多语言混合的文本中,显示出来会有乱码。
因此,Unicode应运而生。Unicode把所有语言都统一到一套编码里,这样就不会再有乱码问题了。
Unicode标准也在不断发展,但最常用的是用两个字节表示一个字符(如果要用到非常偏僻的字符,就需要4个字节)。现代操作系统和大多数编程语言都直接支持Unicode。
现在,捋一捋ASCII编码和Unicode编码的区别:ASCII编码是1个字节,而Unicode编码通常是2个字节。
字母A用ASCII编码是十进制的65,二进制的01000001;
字符0用ASCII编码是十进制的48,二进制的00110000,注意字符'0'和整数0是不同的;
汉字中已经超出了ASCII编码的范围,用Unicode编码是十进制的20013,二进制的01001110 00101101。
你可以猜测,如果把ASCII编码的A用Unicode编码,只需要在前面补0就可以,因此,A的Unicode编码是00000000 01000001。
新的问题又出现了:如果统一成Unicode编码,乱码问题从此消失了。但是,如果你写的文本基本上全部是英文的话,用Unicode编码比ASCII编码需要多一倍的存储空间,在存储和传输上就十分不划算。
所以,本着节约的精神,又出现了把Unicode编码转化为“可变长编码”的UTF-8编码。UTF-8编码把一个Unicode字符根据不同的数字大小编码成1-6个字节,常用的英文字母被编码成1个字节,汉字通常是3个字节,只有很生僻的字符才会被编码成4-6个字节。如果你要传输的文本包含大量英文字符,用UTF-8编码就能节省空间:
字符 ASCII Unicode UTF-8 A 01000001 00000000 01000001 01000001 中 x 01001110 00101101 11100100 10111000 10101101 从上面的表格还可以发现,UTF-8编码有一个额外的好处,就是ASCII编码实际上可以被看成是UTF-8编码的一部分,所以,大量只支持ASCII编码的历史遗留软件可以在UTF-8编码下继续工作。
搞清楚了ASCII、Unicode和UTF-8的关系,我们就可以总结一下现在计算机系统通用的字符编码工作方式:
在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码。
用记事本编辑的时候,从文件读取的UTF-8字符被转换为Unicode字符到内存里,编辑完成后,保存的时候再把Unicode转换为UTF-8保存到文件:
浏览网页的时候,服务器会把动态生成的Unicode内容转换为UTF-8再传输到浏览器:
所以你看到很多网页的源码上会有类似的信息,表示该网页正是用的UTF-8编码。
python字符串
python字符串的几种表达方式,可以使用单引号或双引号括起来:
name = 'lixigli'
user = "lixingli"
print(name,user)
>>lixingli lixingli
如果字符串包含有单引号但不含双引号,则字符串会用双引号括起来,否则用单引号括起来。对于这样的输入字符串,print() 函数会产生更易读的输出。
跨行的字面字符串可用以下几种方法表示。使用续行符,即在每行最后一个字符后使用反斜线来说明下一行是上一行逻辑上的延续: 以下使用 \n 来添加新行:
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n 意味着新行
>>> s # 不使用 print(), \n 包含在输出中
'First line.\nSecond line.'
>>> print(s) # 使用 print(), \n 输出一个新行
First line.
Second line.
以下使用反斜线(\)来续行:
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
print(hello)
注意,其中的换行符仍然要用\n表示--反斜杠后的换行符呗丢弃了。以上例子如下输出:
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
或者,字符串可以被"""(三个双引号)或者'''(三个单引号)括起来。使用三引号时,换行符不需要转义,他们会包含在字符串中,一下的例子使用了一个转义符,避免在最开始产生一个不需要的空行。
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
其输出如下:
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
如果我们使用“原始”字符串,那么\n不会转换成行,行末的反斜杠,以及源码中的换行符 ,都将作为数据包含在字符串内。例如:
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)
注意,r的意思是使用python中的原生字符 将会输出:
This is a rather long string containing\n\
several lines of text much as you would do in C.
字符串运算
字符串可以使用+运算符连接在一起,或者使用*运算符重复:
>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
两个紧邻的字面字符串将自动被串联;商例的第一行也可以写成word = 'Help''A' ;这样的操作只在两个字面间有效,不能随意用于字符串表达式中:
>>> 'str' 'ing' # <- 这样操作正确
'string'
>>> 'str'.strip() + 'ing' # <- 这样操作正确
'string'
>>> 'str'.strip() 'ing' # <- 这样操作错误
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
字符串可以被索引;就像C语言一样,字符串的第一个字符的索引为0,没有单独的字符类型;一个字符就是长度为一的字符串,就像icon编程语言一样,子字符串可以使用分切符来指定:用冒号分隔的两个索引。
word = 'Help you'
print(word[3]) #第四个字符
print(word[:2]) #第0到3个字符
print(word[2:4]) #第3到4个字符
其输出如下: p He lp 默认的分切索引很有用:默认的第一个索引为零,第二个索引默认为字符串可以被分切的长度。
不同于C的字符的是,python字符串不能被改变,想一个索引位置赋值会导致错误:
>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support slice assignment
然而,用组合内容的方法来创建新的字符是简单高效的:
>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
在分切操作字符串时,有一个很有用的规律: s[:i] + s[i:] 等于 s.
>>>word = 'Help A'
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
除了数字,Python也能操作字符串。字符串有几种表达方式,可以使用单引号或双引号括起来:
>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
Python中使用反斜杠转义引号和其它特殊字符来准确地表示。 如果字符串包含有单引号但不含双引号,则字符串会用双引号括起来,否则用单引号括起来。对于这样的输入字符串,print() 函数会产生更易读的输出。 跨行的字面字符串可用以下几种方法表示。使用续行符,即在每行最后一个字符后使用反斜线来说明下一行是上一行逻辑上的延续: 以下使用 \n 来添加新行:
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n 意味着新行
>>> s # 不使用 print(), \n 包含在输出中
'First line.\nSecond line.'
>>> print(s) # 使用 print(), \n 输出一个新行
First line.
Second line.
以下使用 反斜线(\) 来续行:
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
print(hello)
注意,其中的换行符仍然要使用 \n 表示——反斜杠后的换行符被丢弃了。以上例子将如下输出:
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
或者,字符串可以被 """ (三个双引号)或者 ''' (三个单引号)括起来。使用三引号时,换行符不需要转义,它们会包含在字符串中。以下的例子使用了一个转义符,避免在最开始产生一个不需要的空行。
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
其输出如下:
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
如果我们使用"原始"字符串,那么 \n 不会被转换成换行,行末的的反斜杠,以及源码中的换行符,都将作为数据包含在字符串内。例如:
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello) 将会输出:
This is a rather long string containing\n\
several lines of text much as you would do in C.
字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复: >>> word = 'Help' + 'A' >>> word 'HelpA' >>> '<' + word*5 + '>' '' 两个紧邻的字面字符串将自动被串连;上例的第一行也可以写成 word = 'Help' 'A' ;这样的操作只在两个字面值间有效,不能随意用于字符串表达式中:
>>> 'str' 'ing' # <- 这样操作正确
'string'
>>> 'str'.strip() + 'ing' # <- 这样操作正确
'string'
>>> 'str'.strip() 'ing' # <- 这样操作错误
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
字符串可以被索引;就像 C 语言一样,字符串的第一个字符的索引为 0。没有单独的字符类型;一个字符就是长度为一的字符串。就像Icon编程语言一样,子字符串可以使用分切符来指定:用冒号分隔的两个索引。
>>> word[4]
'A'
>>> word[0:2]
'Hl'
>>> word[2:4]
'ep'
默认的分切索引很有用:默认的第一个索引为零,第二个索引默认为字符串可以被分切的长度。
>>> word[:2] # 前两个字符
'He'
>>> word[2:] # 除了前两个字符之外,其后的所有字符
'lpA'
不同于C字符串的是,Python字符串不能被改变。向一个索引位置赋值会导致错误:
>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support slice assignment
然而,用组合内容的方法来创建新的字符串是简单高效的:
>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
在分切操作字符串时,有一个很有用的规律: s[:i] + s[i:] 等于 s.
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
对于有偏差的分切索引的处理方式也很优雅:一个过大的索引将被字符串的大小取代,上限值小于下限值将返回一个空字符串。
>>>word = 'Help A'
>>> word[1:100]
'elpA'
>>> word[10:]
>>> word[2:1]
在索引中可以使用负数,这样会从右往左计数。例如:
>>>word = 'Help A'
>>> word[-1] # 最后一个字符
'A'
>>> word[-2] # 倒数第二个字符
'p'
>>> word[-2:] # 最后两个字符
'pA'
>>> word[:-2] # 除了最后两个字符之外,其前面的所有字符
'Hel'
但要注意, -0 和 0 完全一样,所以 -0 不会从右开始计数!
>>> word[-0] # (既然 -0 等于 0)
'H'
超出范围的负数索引会被截去多余部分,但不要尝试在一个单元素索引(非分切索引)里使用:
>>> word[-100:]
'HelpA'
>>> word[-10] # 错误
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
有一个方法可以让您记住分切索引的工作方式,想像索引是指向字符之间,第一个字符左边的数字是 0。接着,有n个字符的字符串最后一个字符的右边是索引n,例如:
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
第一行的数字 0...5 给出了字符串中索引的位置;第二行给出了相应的负数索引。分切部分从 i 到 j 分别由在边缘被标记为 i 和 j 的全部字符组成。 对于非负数分切部分,如果索引都在有效范围内,分切部分的长度就是索引的差值。例如, word[1:3] 的长度是2。 内置的函数 len() 用于返回一个字符串的长度:
第一行的数字 0...5 给出了字符串中索引的位置;第二行给出了相应的负数索引。分切部分从 i 到 j 分别由在边缘被标记为 i 和 j 的全部字符组成。 对于非负数分切部分,如果索引都在有效范围内,分切部分的长度就是索引的差值。例如, word[1:3] 的长度是2。 内置的函数 len() 用于返回一个字符串的长度:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
python格式化输出
最后一个常见的问题是如何输出格式化的字符串。我们经常会输出类似'亲爱的xxx你好!你xx月的话费是xx,余额是xx'之类的字符串,而xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式。 在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:
>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
另一种方法是:
name = 'hello,{0} 的电话是{1}。'
info = name.format('brutyli',13853966793)
print(info)
其输出如下:
hello,brutyli 的电话是13853966793。
你可能猜到了,%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。
常见的占位符有:
Python进阶之路---1.5python数据类型-字符串的更多相关文章
- Python进阶之路---1.4python数据类型-数字
python入门基础 声明:以后python代码未注明情况下,默认使用python3.x版本 1.python代码基础:print print('hello,python') 1.1pyt ...
- python精进之路1---基础数据类型
python精进之路1---基本数据类型 python的基本数据类型如上图,重点需要掌握字符串.列表和字典. 一.int.float类型 int主要是用于整数类型计算,float主要用于小数. int ...
- Python进阶之路---1.2python版本差异
Python2.*与python3.*版本差异 作为一个初学者,我们应该如何选择python的版本进行学习呢,这两个版本有什么区别呢,接下来让我们简单了解一下,以便我们后续的学习. Python版本差 ...
- python学习笔记(2)数据类型-字符串
字符串是 Python 中最常用的数据类型.我们可以使用引号( ' 或 " )来创建字符串. 创建字符串很简单,只要为变量分配一个值即可.例如: var1 = 'Hello World!' ...
- python进阶之路之文件处理
Python之文件处理 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !imp ...
- python全栈开发笔记---基本数据类型--字符串魔法
字符串: def capitalize(self, *args, **kwargs) test = "aLxs" v = test.capitalize() #capitalize ...
- python进阶之路4.2---装饰器
*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...
- Python进阶之路---1.3python环境搭建
python环境安装 windows python环境安装 下载安装包 https://www.python.org/downloads/ 安装并指定安装目录 C:\python2 ...
- Python进阶之路---1.1python简介
Python简介 Python简介 Python (发音:[ 'paiθ(ə)n; (US) 'paiθɔn ]n.蟒蛇,巨蛇 ),是一种面向对象的解释 ...
随机推荐
- 关于oracle dbms_job 定时执行的内容。
一.设置初始化参数 job_queue_processessql> alter system set job_queue_processes=n;(n>0)job_queue_proces ...
- 怎样取得数组对象和arralist 的长度
数组用length属性 ArrayList用size()方法
- 如何清理多余的Windows桌面右键菜单
删除多余的发送到选项 Win7使用一段时间后,我们可能会装很多软件,这时候右键菜单可能会变得很长,特别是“发送到(Send to)”里面的选项,有时候我们卸载软件之后在右键发送到菜单里还会有残存的选项 ...
- oracle 语句
1.查询TRENDCHART_DLT表中的30条数据,统计字段FRONT01='0',BACK12='0'的条数 select sum(case when FRONT01='0' then 1 els ...
- php随机密码
<?php /* * php自动生成新密码自定义函数(带实例演示) 适用环境: PHP5.2.x / mysql 5.0.x * */ function genPassword($a=1,$b= ...
- Linq中字段数据类型转换问题(Linq to entity,LINQ to Entities 不识别方法"System.String ToString()"问题解决)
1.在工作中碰到这样一个问题: 使用linq时,需要查询两个表,在这两张表中关联字段分别是int,和varchar()也就是string,在linq中对这两个字段进行关联, 如果强制类型转换两个不同类 ...
- C#操作MYSQL遇到0000-00-00日期报错的原因
今天在做一个C#连接MYSQL数据库,并读取数据库的内容,遇到了0000-00-00日期转换报错:unable to convert MySQL date/time value to System.D ...
- 《Linux内核分析》 week5作业-system call中断处理过程
一.使用gdb跟踪分析一个系统调用内核函数 1.在test.c文件中添加time函数与采用c语言内嵌汇编的time函数.具体实现请看下图. 2.然后在main函数中添加MenuConfig函数,进行注 ...
- C++重载操作符
重载的函数操作符,对对象使用起来就像对象是一个函数一样 class A{public:A(int n);int operator()(int n); //需要一个参数,返回int类型void out ...
- javascript 倒计时代码
<script language="javascript" type="text/javascript"> var interval = 1000; ...