Slice
A segment of string is called slice.
# Slice a segment from a string
str = "banana"
print(str[0:2]) # ba
print(str[:2]) # ba
print(str[2:]) # nana
Immutable
Strings are immutable, you can't change them.
# You can't change a string ...
# it is imutable
str = "Hello World"
str[0] = "J"
# TypeError: 'str' object does not support item assignment
Key
To search in a string, use a loop through string.
# Find key in a string
def find_key(str, ch):
i = 0
while i < len(str):
if str[i] == ch:
return i
i = i + 1
return -1
print(find_key("Hello World", "o")) # 4
File
Open words.txt and search through words list.
# Open file and search through words list
# Return number of words with no e in them
import os
file = os.path.dirname(__file__) + "/words.txt"
rows = open(file)
def has_no_e(word):
for letter in word:
if letter == "e":
return False
return True
W = [] # words
E = [] # word with no e
for row in rows:
word = row.strip()
W.append(word)
if (has_no_e(word)):
E.append(word)
print("W: " + repr(len(W)))
print("E: " + repr(len(E)))
Build-in
Strings provide methods for various operations.
# String built-in methods
str = "Hello World"
str = str.upper()
print(str)
# HELLO WORLD
index = str.find("W")
print(index)
# 6
Last update: 182 days ago