Python
/
Strings
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Strings Slice
A slice is a segment of string Strings are immutable str[0:2] #ab str[2:] #cde
Slice
p137 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
p139 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
p141 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
➥ Questions