*Memo for a string, bytes and bytearray:
*Memo for string, bytes and bytearray functions:
- My post explains encode() and decode().
- My post explains upper(), lower() and casefold().
- My post explains swapcase(), title() and capitalize().
- My post explains isupper(), islower() and istitle().
- My post explains count().
- My post explains index().
- My post explains rindex().
- My post explains find().
- My post explains rfind().
- My post explains split().
- My post explains rsplit().
- My post explains splitlines().
- My post explains partition().
- My post explains rpartition().
- My post explains join().
- My post explains replace().
- My post explains removeprefix() and removesuffix().
- My post explains startswith().
- My post explains endswith().
- My post explains center().
- My post explains ljust().
- My post explains rjust().
- My post explains zfill().
- My post explains expandtabs().
- My post explains strip().
- My post explains lstrip().
- My post explains rstrip().
- My post explains maketrans().
- My post explains translate().
- My post explains isdecimal(), isdigit() and isnumeric().
- My post explains isalpha() and isalnum().
- My post explains isascii(), isspace(), isprintable() and isidentifier().
- My post explains iskeyword() and issoftkeyword().
- My post explains ord(), sorted() and reversed().
*Memo for bytearray functions:
*Memo for others:
- My post explains format().
- My post explains format_map().
- My post explains f-strings.
- My post explains a list and the list with indexing.
- My post explains a tuple.
- My post explains a set and the set with copy.
- My post explains a dictionary (1).
- My post explains an iterator (1).
A string(str
):
- is the sequence of zero or more characters whose type is
str
. - shouldn't be huge not to get
I/O error
. - is immutable so it cannot be changed.
- can be created by the string literal
''
,""
,''''''
or""""""
or str() with or without any types of values:- A string literal can have a lot of Unicode characters.
- A string literal can also be used for a docstring.
-
''
or""
is for one line. -
''''''
or""""""
is for one or more lines. - For
str()
, the words type conversion are also suitable in addition to the word creation.
- can be decoded to from a bytes or bytearray by decode():
- For
decode()
, the words creation and type conversion are also suitable in addition to the word encoding.
- For
- can be iterated with a
for
statement. - can be unpacked with an assignment and
for
statement, function and*
but not with**
. - is
False
if it's empty. - can be checked if a specific element is or isn't in it with
in
keyword ornot
andin
keyword respectively. - can be checked if it is or isn't referred to by two variables with
is
keyword ornot
andis
keyword respectively. - can be enlarged with
*
and a number. - can be read 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:
*Memo:
-
\'
is the escape sequence to output'
.
v = '' # Empty str
v = "Hello World"
v = "Lёт's gφ!" # Let's go!
v = "I'm John."
v = 'I\'m John.'
v = '''I'm John.'''
v = """I'm John."""
v = '''Apple Orange Banana Kiwi'''
v = 'Apple' " Orange" '''Banana''' """Kiwi"""
v = '''Apple
Orange
Banana
Kiwi'''
v = """
Apple
Orange
Banana
Kiwi
"""
'These above get no error'
"These above get no error"
'''These above get no error'''
"""These above get no error"""
'''
These above
get no error
'''
"""
These above
get no error
"""
# No error
for v in 'ABC': pass
v1, v2, v3 = 'ABC'
v1, *v2, v3 = 'ABCDEF'
for v1, v2, v3 in ['ABC', 'DEF']: pass
for v1, *v2, v3 in ['ABCDEF', 'GHIJKL']: pass
print([*'ABC', *'DE'])
print(*'ABC', *'DE')
v = 'ABC' * 3
v = '012' * 3
v = '' * 3
# No error
print(**'ABCDE')
print('ABC' * 100000000)
# Error
A string is the sequence of zero or more characters whose type is str
as shown below:
v = "Hello World"
print(v)
# Hello World
print(type(v))
# <class 'str'>
v = '' # Empty str
print(v)
# Nothing
v = "Lёт's gφ!" # Let's go!
print(v)
# Lёт's gφ!
v = "I'm John."
v = 'I\'m John.'
v = '''I'm John.'''
v = """I'm John."""
print(v)
# I'm John.
v = '''Apple Orange Banana Kiwi'''
v = 'Apple' " Orange" ''' Banana''' """ Kiwi"""
print(v)
# Apple Orange Banana Kiwi
v = '''Apple
Orange
Banana
Kiwi'''
print(v)
# Apple
# Orange
# Banana
# Kiwi
v = """
Apple
Orange
Banana
Kiwi
"""
print(v)
#
# Apple
# Orange
# Banana
# Kiwi
#
A string can be iterated with a for
statement as shown below:
for v in 'ABC':
print(v)
# A
# B
# C
A string can be unpacked with an assignment and for
statement, the function and *
but not with **
as shown below:
v1, v2, v3 = 'ABC'
print(v1, v2, v3)
# A B C
v1, *v2, v3 = 'ABCDEF'
print(v1, v2, v3) # A ['B', 'C', 'D', 'E'] F
print(v1, *v2, v3) # A B C D E F
for v1, v2, v3 in ['ABC', 'DEF']:
print(v1, v2, v3)
# A B C
# D E F
for v1, *v2, v3 in ['ABCDEF', 'GHIJKL']:
print(v1, v2, v3)
print(v1, *v2, v3)
# A ['B', 'C', 'D', 'E'] F
# A B C D E F
# G ['H', 'I', 'J', 'K'] L
# G H I J K L
def func(p1='a', p2='b', p3='c', p4='d', p5='e', p6='f'):
print(p1, p2, p3, p4, p5, p6)
func()
# a b c d e f
func(*'ABCD', *'EF')
# A B C D E F
def func(p1='a', p2='b', *args):
print(p1, p2, args)
print(p1, p2, *args)
print(p1, p2, [0, 1, *args, 2, 3])
func()
# a b ()
# a b Nothing
# a b [0, 1, 2, 3]
func(*'ABCD', *'EF')
# A B ('C', 'D', 'E', 'F')
# A B C D E F
# A B [0, 1, 'C', 'D', 'E', 'F', 2, 3]
print([*'ABC', *'DE'])
# ['A', 'B', 'C', 'D', 'E']
print(*'ABC', *'DE')
# A B C D E
print(**'ABCDE')
# TypeError: print() argument after ** must be a mapping, not str
An empty string is False
as shown below:
print(bool('')) # Empty str
# False
print(bool(' ')) # str
# True
A string can be checked if a specific element is or isn't in it with in
keyword or not
and in
keyword respectively as shown below:
v = 'ABCD'
print('B' in v)
# True
print('CD' in v)
# True
print('b' in v)
# False
v = 'ABCD'
print('B' not in v)
# False
print('CD' not in v)
# False
print('b' not in v)
# True
A string can be enlarged with *
and a number as shown below:
v = 'ABC' * 3
print(v)
# ABCABCABC
v = '012' * 3
print(v)
# 012012012
v = '' * 3
print(v)
# Nothing
Be careful, a huge string gets I/O error
as shown below:
v = 'ABC' * 100000000
print(v)
# OSError: [Errno 29] I/O error
A string can be read by indexing or slicing as shown below:
*Memo:
- Indexing can be done with one or more
[index]
. - Slicing can be done with one or more
[start:end:step]
:-
start
(Optional-Default:The index of the 1st element
):- It's a start index(inclusive).
-
end
(Optional-Default:The index of the last element + 1
):- It's an end index(exclusive).
-
step
(Optional-Default:1
):- It's the interval of indices.
- It cannot be zero.
- The
[]
with at least one:
is slicing.
-
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])
# Nothing
A string cannot be changed by indexing or slicing as shown below:
*Memo:
- A del statement can still be used to remove one or more variables themselves.
v = 'abcdef'
v[0] = 'X'
v[2:6] = ['Y', 'Z']
# TypeError: 'str' object does not support item assignment
v = 'abcdef'
del v[0], 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:
v = 'abcdef'
v = list(v)
v[0] = 'X'
v[2:6] = ['Y', 'Z']
v = ''.join(v)
print(v)
# XbYZ
v = 'abcdef'
v = list(v)
del v[0], v[3:5]
v = ''.join(v)
print(v)
# bcd
The variables v1
and v2
always refer to the same string because a string cannot be copied as shown below:
*Memo:
-
is
keyword oris
andnot
keyword can check ifv1
andv2
refer or don't refer to the same string respectively. - copy.copy() and slicing do shallow copy.
-
str()
doesn't do shallow copy. - copy.deepcopy() does deep copy.
-
copy.deepcopy()
should be used because it's safe, doing copy deeply whilecopy.copy()
and slicing aren't safe, doing copy shallowly.
import copy
v1 = 'abcde'
v2 = v1 # v2 refers to the same string as v1.
print(v1) # abcde
print(v2) # abcde
print(v1 is v2, v1 is not v2)
# True False
# v2 refers to the same string as v1.
v2 = copy.copy(v1)
v2 = copy.deepcopy(v1)
v2 = str(v1)
v2 = v1[:]
print(v1) # abcde
print(v2) # abcde
print(v1 is v2, v1 is not v2)
# True False
Top comments (0)