字符串

*: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数据类型-字符串的更多相关文章

  1. Python进阶之路---1.4python数据类型-数字

    python入门基础 声明:以后python代码未注明情况下,默认使用python3.x版本 1.python代码基础:print     print('hello,python')   1.1pyt ...

  2. python精进之路1---基础数据类型

    python精进之路1---基本数据类型 python的基本数据类型如上图,重点需要掌握字符串.列表和字典. 一.int.float类型 int主要是用于整数类型计算,float主要用于小数. int ...

  3. Python进阶之路---1.2python版本差异

    Python2.*与python3.*版本差异 作为一个初学者,我们应该如何选择python的版本进行学习呢,这两个版本有什么区别呢,接下来让我们简单了解一下,以便我们后续的学习. Python版本差 ...

  4. python学习笔记(2)数据类型-字符串

    字符串是 Python 中最常用的数据类型.我们可以使用引号( ' 或 " )来创建字符串. 创建字符串很简单,只要为变量分配一个值即可.例如: var1 = 'Hello World!' ...

  5. python进阶之路之文件处理

    Python之文件处理 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !imp ...

  6. python全栈开发笔记---基本数据类型--字符串魔法

    字符串: def capitalize(self, *args, **kwargs) test = "aLxs" v = test.capitalize() #capitalize ...

  7. python进阶之路4.2---装饰器

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  8. Python进阶之路---1.3python环境搭建

      python环境安装 windows python环境安装 下载安装包     https://www.python.org/downloads/ 安装并指定安装目录     C:\python2 ...

  9. Python进阶之路---1.1python简介

                            Python简介 Python简介 Python (发音:[ 'paiθ(ə)n; (US) 'paiθɔn ]n.蟒蛇,巨蛇 ),是一种面向对象的解释 ...

随机推荐

  1. RecycleView 滑动到底部,加载更多

    android.support.v7 包提供了一个新的组件:RecycleView,用以提供一个灵活的列表试图.显示大型数据集,它支持局部刷新.显示动画等功能,可以用来取代ListView与GridV ...

  2. .NET 编译器(”Roslyn“)介绍

    介绍 一般来说,编译器是一个黑箱,源代码从一端进入,然后箱子中发生一些奇妙的变化,最后从另一端出来目标文件或程序集.编译器施展它们的魔法,它们必须对所处理的代码进行深入的理解,不过相关知识不是每个人都 ...

  3. sql server备份相关

    本文转载自http://dreamfire.blog.51cto.com/418026/152075/ 感谢作者的分享!!   数据库没有备份---应如何还原丢失的数据   环境描述: 某公司装了一台 ...

  4. 用Spring Boot零配置快速创建web项目(1)

    一.Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人 ...

  5. Ubuntu 13.10 Mono安装历程

    这两天捣鼓一下Mono,记录一下自己所遇到的问题,已经解决办法 首先,先打开gnome-terminal 1. 先更新的一下系统 sudo apt-get update sudo apt-get up ...

  6. Memcached使用手册

    memcached简介 1.memcached是一个高性能的分布式的内存对象缓存系统,通过在内存里维护一个统一的巨大的hash表,它能够用来存储各种格式的数据,包括图像.视频.文件以及数据库检索的结果 ...

  7. ADODB的应用

    <?php include_once ('adodb5/adodb.inc.php'); $db = NewADOConnection ('mysql'); $db->Connect(&q ...

  8. IIS开启伪静态后html静态页面无法访问的解决方法

    IIS开启伪静态后,发现原本存在的html静态页面无法访问了,显示的404错误.网上查了下,是因为实现伪静态就是使用 URLRewriter 来映射后缀,会把asp等动态页面映射成html,但是原来存 ...

  9. ASP.NET MVC5中的数据注解

    ASP.NET MVC5中Model层开发,使用的数据注解有三个作用: 数据映射(把Model层的类用EntityFramework映射成对应的表) 数据验证(在服务器端和客户端验证数据的有效性) 数 ...

  10. 项目设计&重构&性能优化

    漫谈项目设计&重构&性能优化 重构的好处:重构能够改进软件设计,随着项目需求的变更,项目体积的变大早已与最初的设计大相径庭,代码结构变得凌乱.复杂,如果不进行重构,则很难添加新的功能. ...