- The Python Workshop
- Andrew Bird Dr Lau Cher Han Mario Corchero Jiménez Graham Lee Corey Wade
- 399字
- 2021-06-11 12:51:26
Slicing
A slice is a subset of a string or other element. A slice could be the whole element or one character, but it's more commonly a group of adjoining characters.
Let's say you want to access the fifth through eleventh letters of a string. So, you start at index 4 and end at index 10, as was explained in the previous Indexing section. When slicing, the colon symbol (:) is inserted between indices, like so: [4:10].
There is one caveat. The lower bound of a slice is always included, but the upper bound is not. So, in the preceding example, if you want to include the 10th index, you must use [4:11].
You should now have a look at the following example for slicing.
Retrieve the fifth through eleventh letters of San Francisco, which you used in the previous Indexing section:
destination[4:11]
You should get the following output:
'Francis'
Retrieve the first three letters of destination:
destination[0:3]
You should get the following output:
'San'
There is a shortcut for getting the first n letters of a string. If the first numerical character is omitted, Python will start at the 0th index.
Now, to retrieve the first eight letters of destination using the shortcut, use the following code:
destination[:8]
You should get the following output:
'San Fran'
Finally, to retrieve the last three letters of destination, use this code:
destination[-3:]
You should get the following output:
'sco'
The negative sign, -, means that we start at the third-to-last letter, and the colon means that we go to the end.
Strings and Their Methods
You started with string syntax, before moving on to a variety of ways to concatenate strings. You looked at useful built-in functions including len() and examined a sample of string methods. Next, you casted numbers as strings and vice versa.
The input() function is used to access user input. This really extends what you can do. Responding to user feedback is a core element of programming that you will continue to develop. Finally, you closed with two powerful tools that developers frequently use: indexing and slicing.
There is a great deal more to learn about strings. You will encounter additional problems and methods throughout this book. This introductory chapter is meant to equip you with the basic skills needed to handle strings going forward.
Next, you will learn how to branch programs using conditionals and Booleans.
- 大數(shù)據(jù)項目管理:從規(guī)劃到實現(xiàn)
- JavaScript實例自學(xué)手冊
- Python Artificial Intelligence Projects for Beginners
- Visual C# 2008開發(fā)技術(shù)實例詳解
- 機艙監(jiān)測與主機遙控
- 空間站多臂機器人運動控制研究
- 突破,Objective-C開發(fā)速學(xué)手冊
- 基于Xilinx ISE的FPAG/CPLD設(shè)計與應(yīng)用
- PVCBOT機器人控制技術(shù)入門
- Word 2007,Excel 2007辦公應(yīng)用融會貫通
- 工業(yè)自動化技術(shù)實訓(xùn)指導(dǎo)
- Mastering Text Mining with R
- AVR單片機工程師是怎樣煉成的
- 西門子S7-1200/1500 PLC從入門到精通
- 新一代人工智能與語音識別