今日已更新 133 条资讯 | 累计 29586 条内容
关于我们

Introduction to Python Module Four Part Three: Slicing

Sarah Bartley 2026年08月04日 05:26 8 次阅读 来源:Dev.to

Sololearn’s Introduction to Python course is wrapping up today with a brand new topic. Today’s post is wrapping up module four by introducing. You’ll learn what slicing is and how to slice a list in Python. Sequences like lists and strings are ordered content. Ordered content is great for indexing and slicing. In addition to learning about slicing, Sololearn shares some advanced slicing and indexing tips to help you with your code. Slicing Slicing lets developers take portions from a list that they need. You’ll be slicing lists all the time in your Python code. At Coding with Kids, the students were slicing lists as they were building games. To slice a list, put the variable name of list followed by an opening square bracket. Put the index you want to start slicing at. Place a colon (:) after this. Put the index when you want to stop slicing at then place the closing square brackets. Here’s an example of slicing in action. I created a variable called pizza_toppings with a list of strings assigned to them. The starting index is inclusive while the stopping index is exclusive. pizza_toppings = [ " pepperoni " , " mushrooms " , " onions " , " peppers " , " broccoli " , " sausage " ] print ( pizza_toppings [ 0 : 3 ]) # print pepperoni, mushrooms, and onions The line underneath the list is slicing the first 3 toppings from the list. I’m printing them to the console to make sure these three are displaying. If you see the wrong toppings or too many items, double check the index you are starting and ending with. Slicing a String Strings can be sliced to in the same way we did the example above. Here’s a variable with a string assigned to it. If I want to slice certain letters in the string, I will put the indexes where I should start and stop at. pizza = " pepperoni " print ( pizza [ 0 : 6 ]) # print pepper When I sliced this string, I was able to move data from a sequence. In this example, I’m able to create a brand new string. If you look at the the pizza topping example

本文内容来源于互联网,版权归原作者所有
查看原文