Skip to content

Python Journey

My Coding Blog

Menu
  • Links
Menu

Python>>Strings: Indexing and Slicing

Posted on August 23, 2022August 24, 2022 by coden00b

I will be showing more examples of indexing and slicing as a form of my practice to familiarize this. From the previous lesson/posts, the syntax for slicing as follows:

string[start : end : step]

Example1: (Indexing and Slicing in Strings)

W r i t e C o d e O n l i n e
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

-print the word “Online”

>> str=’WriteCodeOnline’
>>> print(str)
WriteCodeOnline
>>> print(str[9:])
Online

-print the word “Onli”

>> print(str[9:13])
Onli
>>>

-print the word “teCo”

>>> print(str[3:7])
teCo

-print the word “Online” using the negative indexing

print(str[-6:])
Online

-print the word “Onli” using negative indexing

>>> print(str[-6:-2])
Onli

-print the word “teCo” using negative indexing

>> print(str[-12:-8])
teCo

Example2: (Indexing and Slicing in Lists)

Write Code Online
0 1 2
-3 -2 -1

Indexing:

strlist = [‘Write’, ‘Code’, ‘Online’]
>>> print(strlist)
[‘Write’, ‘Code’, ‘Online’]
>>> print(strlist[0])
Write
>>> print(strlist[2])
Online
>>> print(strlist[-2])
Code

>> print(strlist[-2:-1])
[‘Code’]

Example3: Steps(Stride)

The “step” parameter is optional and the default is 1. It can be either positive or negative.

As mentioned about, just want to repeat again

string[start : end : step]

start-position end-position increment

e.g.
WRITECODE

Let say we want to specify the step of slicing by 2

[start:stop:2]

>> str = ‘WRITECODE’
>>> print(str)
WRITECODE
>>> print(str[::])
WRITECODE
>>> print(str[::1])
WRITECODE
>>> print(str[::2])
WIEOE

 

Let take this example:

>> print(str[1:8:3])
RED

str[1:8:3] = W  R   I   T  E  C  O  D  E

0   1  2   3  4  5  6  7   8

-starts  from R and ends on D, as (E will not include)

-steps will start counting from R, take R, then count 0,1,2,3 then take that character, from E count again 0,1,2,3 and take that character

More example

-Display letter “t” in one line for word “Writecode”

>> ‘Writecode'[3:4]
‘t’

 

More indexing and slicing on next post

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • The Zen of Python
  • Python>>String Interpolation and Formatting
  • Python>>String Methods
  • Python>>String Concatenation
  • Python>>Strings: Indexing and Slicing

Recent Comments

No comments to show.

Archives

  • January 2023
  • August 2022

Categories

  • Blog
  • Data Types