8.1 A string is a sequence
A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

>>> fruit = 'banana'
>>> letter = fruit[1]

The second statement selects character number 1 from fruit and assigns it to letter. The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name). But you might not get what you expect:

>>> print letter
a

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the index is an offset from the beginning of the string, and the offset of the first letter is zero.

>>> letter = fruit[0]
>>> print letter
b

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the 2th (“two-eth”) letter. You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get:

>>> letter = fruit[1.5]
TypeError: string indices must be integers, not float

8.2 len
len is a built-in function that returns the number of characters in a string:

>>> fruit = 'banana'
>>> len(fruit)
6

To get the last letter of a string, you might be tempted to try something like this:

>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range

The reason for the IndexError is that there is no letter in 'banana' with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:

>>> last = fruit[length-1]
>>> print last
a

Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.

8.3 Traversal with a for loop
A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop:

index = 0
while index < len(fruit):
letter = fruit[index]
print letter
index = index + 1

This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string.
Another way to write a traversal is with a for loop:

for char in fruit:
print char

Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left.
The following example shows how to use concatenation (string addition) and a for loop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskey’s book MakeWay for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order:

prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print letter + suffix
The output is:
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

Of course, that’s not quite right because “Ouack” and “Quack” are misspelled.

8.4 String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in Figure 8.1.
If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:

>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:

>>> fruit = 'banana'
>>> fruit[3:3]
''

An empty string contains no characters and has length 0, but other than that, it is the same as any other string.

8.5 Strings are immutable
It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example:

>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment

The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence.
The reason for the error is that strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original:

>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world!

This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string.

8.6 Searching
What does the following function do?

def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1

In a sense, find is the opposite of the [] operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns -1.

This is the first example we have seen of a return statement inside a loop. If word[index] == letter, the function breaks out of the loop and returns immediately.
If the character doesn’t appear in the string, the program exits the loop normally and returns -1.

This pattern of computation—traversing a sequence and returning when we find what we are looking for—is called a search.

8.7 Looping and counting
The following program counts the number of times the letter a appears in a string:

word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print count

This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result—the total number of a’s.

8.8 String methods
A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper().

>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method
takes no argument.

A method call is called an invocation; in this case, we would say that we are invoking upper on the word.

As it turns out, there is a string method named find that is remarkably similar to the function we wrote:

>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1

In this example, we invoke find on word and pass the letter we are looking for as a parameter. Actually, the find method is more general than our function; it can find substrings, not just characters:

>>> word.find('na')
2

It can take as a second argument the index where it should start:

>>> word.find('na', 3)
4

And as a third argument the index where it should stop:

>>> name = 'bob'
>>> name.find('b', 1, 2)
-1

This search fails because b does not appear in the index range from 1 to 2 (not including 2).

8.9 The in operator
the following function prints all the letters from word1 that also appear in word2:

def in_both(word1, word2):
for letter in word1:
if letter in word2:
print letter

With well-chosen variable names, Python sometimes reads like English. You could read this loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter.”

Here’s what you get if you compare apples and oranges:

>>> in_both('apples', 'oranges')
a
e
s

8.10 String comparison
The relational operators work on strings. To see if two strings are equal:

if word == 'banana':
print 'All right, bananas.'

Other relational operations are useful for putting words in alphabetical order:

if word < 'banana':
print 'Your word,' + word + ', comes before banana.'
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.'
else:
print 'All right, bananas.'

Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters, so:
Your word, Pineapple, comes before banana. A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.

[全文摘自"Think Python"]

Think Python - Chapter 8 - Strings的更多相关文章

  1. <Web Scraping with Python>:Chapter 1 & 2

    <Web Scraping with Python> Chapter 1 & 2: Your First Web Scraper & Advanced HTML Parsi ...

  2. Think Python - Chapter 18 - Inheritance

    In this chapter I present classes to represent playing cards, decks of cards, and poker hands.If you ...

  3. Think Python - Chapter 17 - Classes and methods

    17.1 Object-oriented featuresPython is an object-oriented programming language, which means that it ...

  4. Think Python - Chapter 12 Tuples

    12.1 Tuples are immutable(元组是不可变的)A tuple is a sequence of values. The values can be any type, and t ...

  5. Think Python - Chapter 11 - Dictionaries

    Dictionaries A dictionary is like a list, but more general. In a list, the indices have to be intege ...

  6. Think Python - Chapter 10 - Lists

    10.1 A list is a sequenceLike a string, a list is a sequence of values. In a string, the values are ...

  7. Think Python - Chapter 03 - Functions

    3.1 Function callsIn the context of programming, a function is a named sequence of statements that p ...

  8. Natural Language Processing with Python - Chapter 0

    一年之前,我做梦也想不到会来这里写技术总结.误打误撞来到了上海西南某高校,成为了文科专业的工科男,现在每天除了膜ha,就是恶补CS.导师是做计算语言学的,所以当务之急就是先自学计算机自然语言处理,打好 ...

  9. Think Python - Chapter 16 - Classes and functions

    16.1 TimeAs another example of a user-defined type, we’ll define a class called Time that records th ...

随机推荐

  1. [转]Linux下用gcc/g++生成静态库和动态库(Z)

    Linux下用gcc/g++生成静态库和动态库(Z) 2012-07-24 16:45:10|  分类: linux |  标签:链接库  linux  g++  gcc  |举报|字号 订阅     ...

  2. MyEclipse8.6 破解以及注册码

    建立JAVA工程文件.将以下Java代码拷贝至类中并执行即可. 注册码: register name: bobo9360013   Serial:oLR8ZC-855550-6065705698041 ...

  3. discuz 同步登录问题

    最近一直在搞discuz论坛的二次开发,发现在论坛登录或退出的时候应用却没有同步登录或同步退出,这下子麻烦了,后来查看,原来没有产生js的同步代码,查找原因,发现$_G['setting']['all ...

  4. Debug的F5~F8用法

    快捷键(F6)单步执行程序,遇到方法时跳过. 快捷键(F8)执行此断点到最后,进入下一个断点开始之处. 快捷键(F5)单步执行程序,遇到方法时进入. 快捷键(F7)单步执行程序,从当前方法跳出.

  5. js 获取div 图片高度

    使用jquery获取网页中图片的高度其实很简单,有两种常用的方法都可以打到我们的目的 $("img").whith();(返回纯数字) $("img").css ...

  6. LibLinear(SVM包)使用说明之(一)README

    转自:http://blog.csdn.net/zouxy09/article/details/10947323/ LibLinear(SVM包)使用说明之(一)README zouxy09@qq.c ...

  7. [开发笔记]-多线程异步操作如何访问HttpContext?

    如何获取文件绝对路径? 在定时器回调或者Cache的移除通知中,有时确实需要访问文件,然而对于开发人员来说, 他们并不知道网站会被部署在哪个目录下,因此不可能写出绝对路径, 他们只知道相对于网站根目录 ...

  8. WP8.1 Study5:Data binding数据绑定

    一.数据绑定 最简单的编程UI控件的方法是写自己的数据来获取和设置控件的属性,e.g. , textBox1.Text = "Hello, world"; 但在复杂的应用程序,这样 ...

  9. python多线程与多进程

    由于python的内存回收机制不是线程安全的,所以就有了GIL保证每个进程内,同一时刻最多只有一个线程在运行. 于是,对于python的多线程来讲,其实同一时刻依然只有一个线程在运行.而且由于线程切换 ...

  10. App Store--心酸的上线路,说说那些不可思议的被拒理由

    yoyeayoyea 您的应用包括色情内容(色情交易,色情展示). 原因是我们的销售人员,把几张艺术照放在个人相册里(头像),换成卡通头像,通过.    颜小风 被拒很正常 一次通过不正常. 之前上线 ...