《Python for Beginners》学习笔记(2)

《Python for Beginners》为LearnStreet上的Python入门课程。本节主要学习内容为字符串

一、基本概念
1. Indexing - References a specific element of a sequence. The first element in a sequence is found at the index 0. To use a single element, call it with [], like this: variable_name[index].
首元素的索引值为0。

2. Negative Indexing - This allows you to reference values starting with the last element in a sequence. Count backwards from the end, starting with the index variable_name[-1].
负数索引值表示从末尾元素开始从后向前数的索引值,末尾元素从variable_name[-1]开始。

3. Slicing - Slicing allows you to use a particular subset of elements in a sequence. The format for slicing is variable_name[x:y] , where it goes from the xth element and up to (but not including) the yth element.
variable_name[x:y]表示从第x个元素到第y个元素(不含第y个元素)之间的元素序列。

4. Membership - uses the "in" operator to check if a string is found within a larger string.
使用in操作符检测一个字符串是否属于另一个大字符串。

5. A function is basically a way to give several lines of code to one variable name. When the function is called, all of the code in the function is run.
函数即将多行代码赋予一个变量名,调用该函数就执行函数中的代码。

二、编程练习
1. 字符串合并(串联)
>teach = "Learn"
>teach = teach + "Street"
>teach
=>LearnStreet
(注:=>后面为输出结果)

2. 负索引值
>py = "python"
>py[-2]
=> 'o'

3. 字符串切片
>w = "watermelon"
>w[0:5]
=> 'water'

4. 字符(串)检索
>"i" in "team"
=> False

5.使用len()函数计算字符串长度
>len("hello")
=> 5

>len(phrase)
=> 184
(注:phrase为已声明过的字符串变量)

6.小测验
在字符串变量book所包含的字符串的前半部分中检索是否含有"peanut"字符串。

>"peanut" in book[0:(len(book)/2)]
=> True

(本文完)

原文地址:https://www.cnblogs.com/geekham/p/2944926.html