Python
/
Strings
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
Slice
➟
➟
Last update: 03-12-2021
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
String are immutable, you can't change it.
# 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 github Strings