minte9
LearnRemember



pag. 137-141

Immutable

 
""" Strings are immutable, you can't change them
"""

str = "Hello World"
try:
    str[0] = "J"  # invalid statement

except TypeError as e:
    print('TypeError:', e)

"""
    TypeError: 'str' object does not support item assignment
"""

Slices

 
""" A string is a sequence of characters
    We can slice a portion of it with [:]
"""

str = "banana"

# String slices
s1 = str[0:2]   # first two chars
s2 = str[:2]    # up to index 2
s3 = str[2:]    # from index 2 to end

print(s1, s2, s3)

"""
    ba ba nana
"""

Search Key

 
""" To search in a string, use a loop
    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

key = find_key("Hello World", "o")
print(key)  

"""
    4
"""

in Operator

 
""" The `in` is a boolean operator
    Returns True if the fist string appears as a substring in the second one
    The repr() function returns a printable representation of the given object
""" 

import os

file = os.path.dirname(__file__) + "/../data/words.txt"
rows = open(file)

def exists(word):
    for char in word:

        if char == "e":
            return False
            
    return True

W = []  # words
E = []  # word with no e

for row in rows:
    word = row.strip()
    W.append(word)

    if (exists(word)):
        E.append(word)  
    
print("Words: " + repr(len(W)))
print("Words (with char e): " + repr(len(E)))

"""
    Words: 113783
    Words (with char e): 37621
"""



  Last update: 97 days ago