官术网_书友最值得收藏!

Strings

Strings are immutable sequence objects, with each character representing an element in the sequence. As with all objects, we use methods to perform operations. Strings, being immutable, do not change the instance; each method simply returns a value. This value can be stored as another variable or given as an argument to a function or method.

The following table is a list of some of the most commonly used string methods and their descriptions:

Strings, like all sequence types, support indexing and slicing. We can retrieve any character from a string by using its index s[i]. We can retrieve a slice of a string by using s[i:j], where i and j are the start and end points of the slice. We can return an extended slice by using a stride, as in the following: s[i:j:stride]. The following code should make this clear:

The first two examples are pretty straightforward, returning the character located at index 1 and the first seven characters of the string, respectively. Notice that indexing begins at 0. In the third example, we are using a stride of 2. This results in every second character being returned. In the final example, we omit the end index and the slice returns every second character in the entire string.

You can use any expression, variable, or operator as an index as long as the value is an integer, for example:

Another common operation is traversing through a string with a loop, for example:

Given that strings are immutable, a common question that arises is how we perform operations such inserting values. Rather than changing a string, we need to think of ways to build new string objects for the results we need. For example, if we wanted to insert a word into our greeting, we could assign a variable to the following:

As this code shows, we use the slice operator to split the string at index position 5 and use + to concatenate. Python never interprets the contents of a string as a number. If we need to perform mathematical operations on a string, we need to first convert them to a numeric type, for example:

主站蜘蛛池模板: 沙坪坝区| 嘉兴市| 思茅市| 彩票| 千阳县| 阳朔县| 嘉兴市| 敦煌市| 扶沟县| 顺昌县| 阿鲁科尔沁旗| 呼和浩特市| 思南县| 桐城市| 深水埗区| 夹江县| 泽普县| 大洼县| 达州市| 闵行区| 清流县| 万州区| 新平| 孟津县| 扎鲁特旗| 海盐县| 临泉县| 石首市| 株洲县| 瑞安市| 淄博市| 莆田市| 六安市| 根河市| 泗洪县| 陈巴尔虎旗| 株洲县| 明光市| 介休市| 尤溪县| 扎鲁特旗|