*Memos:
- My post explains str().
- My post explains encode() and decode().
- My post explains upper(), lower(), casefold(), swapcase(), title(), capitalize(), isupper(), islower() and istitle().
- My post explains count(), startswith() and endswith().
- My post explains find(), rfind(), index() and rindex().
- My post explains replace(), removeprefix(), removesuffix() and join().
A string:
- is a sequence of zero or more characters.
- is immutable so it cannot be changed.
- can be created with
''
or""
or str() with or without many kinds of objects. - can be enlarged with
*
and a number. - can be accessed but cannot be changed by indexing or slicing.
Be careful, a huge string gets I/O error
.
''
or ""
can create a string as shown below. *\'
is the escape sequence to output '
:
v = '' # Empty string
v = "" # Empty string
v = 'Hello'
v = "Hello"
v = 'I\'m John.'
v = "I'm John."
# No error
A string is a sequence of zero or more characters as shown below:
v = 'abcde'
print(v) # abcde
A string can be enlarged with *
and a number as shown below:
v = 'abc' * 3
print(v) # abcabcabc
Be careful, a huge string gets I/O error
as shown below:
v = 'abc' * 100000000
print(v) # line 3, in OSError: [Errno 29] I/O error
You can access a string by indexing or slicing as shown below:
v = 'abcdefgh'
print(v) # abcdefgh
print(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7])
print(v[-8], v[-7], v[-6], v[-5], v[-4], v[-3], v[-2], v[-1])
# a b c d e f g h
v = 'abcdefgh'
print(v[:])
print(v[::])
# abcdefgh
print(v[::2])
# aceg
print(v[::-2])
# hfdb
print(v[2:])
print(v[-6:])
print(v[2::])
print(v[-6::])
# cdefgh
print(v[2::2])
print(v[-6::2])
# ceg
print(v[2::-2])
print(v[-6::-2])
# ca
print(v[:6])
print(v[:-2])
print(v[:6:])
print(v[:-2:])
# abcdef
print(v[:6:2])
print(v[:-2:2])
# ace
print(v[:6:-2])
print(v[:-2:-2])
# h
print(v[2:6])
print(v[-6:-2])
print(v[2:6:])
print(v[-6:-2:])
# cdef
print(v[2:6:2])
print(v[-6:-2:2])
# ce
print(v[2:6:-2])
print(v[-6:-2:-2])
# Empty string
You cannot change a string because it's immutable as shown below. *A del statement can still be used to remove a variable itself:
v = 'abcdef'
v[0] = 'X'
# v[-6] = 'X'
v[2:6] = ['Y', 'Z']
# TypeError: 'str' object does not support item assignment
v = 'abcdef'
del v[0]
# del v[-6]
del v[3:5]
# TypeError: 'str' object does not support item deletion
v = 'abcdef'
del v
print(v) # NameError: name 'v' is not defined
If you really want to change a string, use list() and join() as shown below. *join()
can concatenate the zero or more strings in an iterable.
v = 'abcdef'
v = list(v) # Here
v[0] = 'X'
# v[-6] = 'X'
v[2:6] = ['Y', 'Z']
v = ''.join(v) # Here
print(v) # XbYZ
v = 'abcdef'
v = list(v) # Here
del v[0]
# del v[-6]
del v[3:5]
v = ''.join(v) # Here
print(v) # bcd