string slicing in python.

sequence types can be sliced in python.

str is also immutable sequence type that means str objects can be sliced.
so, I will introduce how to slice string in this page.

I think slicing is very good tool in python. so, if you are familiar with this, it will be very helpful in the future.

there are 3 types to slice string like below.

s[i]
s[i:j]
s[i:j:k]

i and j are index of string.
k is the step.

when you set only i, you can get ith character of string.
and if you set i and j, you can get sub-string from i to j.
if you set i, j and k, you can get sub-string from i to j with k step.

i is included in the range. and j is not included in the range.

the index can be negative value.
for example, -1 means last one of string. -2 means second last one of string.

let's check them in code.


strSource = "hello python"

print(strSource[0])
print(strSource[0:5])
print(strSource[0:12:2])

print()
print(strSource[-1])
print(strSource[6:-1])
print(strSource[6:-1])



Comments

Popular posts from this blog

making menubar and menu on QML

QSizePolicy Fixed example in pyside2

let's start QML programming with PySide2