String Slicing 1/2
To get get a substring from a string, you have to use slice()
function.
The syntax of slice()
function:.
slice(start: end: step)
respectively:
start -- the index from which to start slicing.
end -- the index at which the slicing ends.
step -- this parameter determines the increments between the indices.
Ending index is
up to but not including
.
Indexing starts from 0.
It's time for an example.
99
1
2
3
4
5
6
7
8
9
10
# String slicing
string ='Python'
# Using slice constructor
string_1 = slice(4)
string_2 = slice(2, 6, 2)
string_3 = slice(-1, -5, -2)
print(string[string_1])
print(string[string_2])
print(string[string_3])
12345678910# String slicing string ='Python' # Using slice constructor string_1 = slice(4) string_2 = slice(2, 6, 2) string_3 = slice(-1, -5, -2) print(string[string_1]) print(string[string_2]) print(string[string_3])
Taak
Swipe to start coding
You have such string hello, world
. Using slice()
constructor you have to get such string: ll
, eowl
, world
. Use only positive indexing.
Oplossing
99
1
2
3
4
5
6
7
8
9
10
11
12
# String slicing
string ='hello, world'
# Using slice constructor
string_1 = slice(2, 4, 1)
string_2 = slice(1, 12, 3)
string_3 = slice(7, 12, 1)
print(string[string_1])
print(string[string_2])
print(string[string_3])
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 3. Hoofdstuk 5
99
1
2
3
4
5
6
7
8
9
10
11
12
13
# String slicing
string ='hello, world'
# Using slice constructor
# Here you have to get ll
string_1 = slice(_ _ _, _ _ _, _ _ _)
# Here you have to get eowl
string_2 = slice(_ _ _ , _ _ _, _ _ _)
# Here you have to get world
string_3 = slice(_ _ _, _ _ _, _ _ _)
print(string[string_1])
print(string[string_2])
print(string[string_3])
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.