C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The item access, s[n], requires only one number. This is an index access. It can be thought of as a 1-element slice.
Tip: A skip value is rarely helpful on strings. It serves mostly to make programs harder to understand.
Python program that slices string
s = "abcdefghijklmnopqrs"
# Loop over some indexes.
for n in range(2, 4):
# Print slices.
print(n, s[n])
print(n, s[n:n + 2])
print(n, s[n:n + 3])
print(n, s[n:n + 4:2])
print(n, s[n:n + 6:2])
Output
2 c
2 cd
2 cde
2 ce
2 ceg
3 d
3 de
3 def
3 df
3 dfh
Python program that gets one-character substring
value = "web"
# Loop over every index in string.
for index in range(0, len(value)):
# Get one-character substring.
char = value[index]
# Display substring.
print(char)
# Test substring.
if char == "w":
print(True)
Output
w
True
e
b
Tip: The length of the slice is the difference between the two arguments (subtract the first from the second).
Python program that takes substrings
string = "abcdefgh"
# Two-character substring.
two = string[0:2]
# Three-character substring.
three = string[0:3]
# Four-character substring.
four = string[0:4]
# Five-character substring.
five = string[0:5]
print(two)
print(three)
print(four)
print(five)
Output
ab
abc
abcd
abcde
Python program that uses offset
string = "abcdefgh"
# Three characters starting at index 2.
offset = 2
length = 3
sliced = string[offset:offset+length]
print(sliced)
Output
cde
Python program that omits start index
value = "rainy day"
# Omitting the start means start at 0.
test = value[:2]
print("OMIT START:", test)
test = value[0:2]
print("START AT 0:", test)
Output
OMIT START: ra
START AT 0: ra
Python program that gets last two characters
value = "apple"
# Get last two characters.
end = value[-2:]
print(end)
Output
le
TypeError: This error is used for many problems in the Python language. It indicates invalid type usage. Try python, Errors.
Python program that causes error
value = "dotCodex"
value[3] = " net " # Does not work.
print(value)
Output
Traceback (most recent call last):
File "...\file.py", line 6, in <module>
value[3:] = " net "
TypeError: 'str' object does not support item assignment
Result: When we use first_words, we extract the first words separated by spaces. A slice is used to take the substring.
Python program that uses slice, gets first words
def first_words(input, words):
for i in range(0, len(input)):
# Count spaces in the string.
if input[i] == ' ':
words -= 1
if words == 0:
# Return the slice up to this point.
return input[0:i]
return ""
# Test our method.
test = "Stately, plump Buck Mulligan came from the stairhead."
result = first_words(test, 4)
print(result)
Output
Stately, plump Buck Mulligan
Tip: We can place all possible substrings in a dictionary, and then do constant-time lookups to search a string.
DictionaryFor: We use the for-range loop in Python to iterate through all lengths and start indexes in the source string.
forPython program that generates all possible substrings
test = "abcdefghi"
# Loop over possible lengths.
for length in range(1, len(test)):
# Loop over possible start indexes.
for start in range(0, len(test) - length + 1):
# Take substring and print it.
part = test[start:length + start]
print(part)
Output
a
b
c
d
e
f
g
h
i
ab
bc
cd
de
ef
fg
gh
hi
abc
bcd
cde
def
efg
fgh
ghi
abcd
bcde
cdef
defg
efgh
fghi
abcde
bcdef
cdefg
defgh
efghi
abcdef
bcdefg
cdefgh
defghi
abcdefg
bcdefgh
cdefghi
abcdefgh
bcdefghi