![](http://static.tieba.baidu.com/tb/editor/images/qpx_n/b01.gif)
#的重头戏,所以,就从强大的string类开始吧~~
#之前在python学习资料一帖中说的英文教程就是这个,英文本身并不生涩,而且介绍的也是简明而又突出重点的。所以,索性就和大家分享一下。以后会陆续更新
#每次更新的结尾都有下期预告哦~~
Preview(前言):
也许很多人都学习过C++中的string类,习惯了其中便捷的方法 — strcpy/strlen/strcmp... 以及简单的 '+' 拼接。Python同样具备这些强大的功能,而且更加简洁、便于实现。相信你会慢慢的爱上这门美妙的编程语言。
![](http://static.tieba.baidu.com/tb/editor/images/jd/j_0002.gif)
##############################################################
Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used. Backslash escapes work the usual way within both single and double quoted literals -- e.g. \n \' \". A double quoted string literal can contain single quotes without any fuss (e.g. "I didn't do it") and likewise single quoted string can contain double quotes. A string literal can span multiple lines, but there must be a backslash \ at the end of each line to escape the newline. String literals inside triple quotes, """ or ''', can multiple lines of text.Python
有一种被称作 "str" 的内置字符串类,包含了很多便捷的功能(另外还有一种稍早一点的"string"模块,不推荐大家使用)。理论上,一个字符串常量既可以由双引号引用("xxx"),也可以由单引号引用('xxx'),尽管单引号使用更加频繁。不论是在单引号还是双引号引用的字符串中,反斜杠的作用都是相同的(通常用作转义字符, 类似于C/C++中的: \n 换行)-- 例如:\n \' \"。在一个由双引号引用的字符串中使用单引号并不会引起歧义(例如:"I didn't do it" -- 解释器知道该字符串是从第一个双引号开始,到第二个双引号结束,中间的单引号并不会引起混淆),类似的在单引号引用的字符串中使用双引号也不会引起歧义。一个字符串可以跨越多行,但必须在行尾用反斜杠进行转义。使用三引号("""xxx""" 或者 '''xxx''')引用的字符串的跨行则不需要使用反斜杠进行转义。
Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style). Since strings can't be changed, we construct *new* strings as we go to represent computed values. So for example the expression ('hello' + 'there') takes in the 2 strings 'hello' and 'there' and builds a new string 'hellothere'.
Python的字符串类型是“不可变”的,因此,一旦创建就不能对它进行修改(这有一些类似于Java的字符串类型)。由于字符串的这一不可变性质,当我们试图对字符串进行计算时,我们实际上是创建了一个新的字符串副本。例如这样的一个表达式('hello' + 'there'),对'hello'和'there'这两个字符串的拼接操作,解释器会创建一个新的 'hellothere' 副本,并将这个副本返回,而不是直接修改 'hello' 或 'there' 这两个原串。
Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++, Python uses zero-based indexing, so if str is 'hello' str[1] is 'e'. If the index is out of bounds for the string, Python raises an error. The Python style (unlike Perl) is to halt if it can't tell what to do, rather than just make up a default value.