DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

String in Python (1)

Buy Me a Coffee

*Memo for a string, bytes and bytearray:

*Memo for string, bytes and bytearray functions:

*Memo for bytearray functions:

*Memo for others:

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.
  • 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 or not and in keyword respectively.
  • can be checked if it is or isn't referred to by two variables with is keyword or not and is 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 
Enter fullscreen mode Exit fullscreen mode

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'> 
Enter fullscreen mode Exit fullscreen mode
v = '' # Empty str  print(v) # Nothing 
Enter fullscreen mode Exit fullscreen mode
v = "Lёт's gφ!" # Let's go!  print(v) # Lёт's gφ! 
Enter fullscreen mode Exit fullscreen mode
v = "I'm John." v = 'I\'m John.' v = '''I'm John.''' v = """I'm John.""" print(v) # I'm John. 
Enter fullscreen mode Exit fullscreen mode
v = '''Apple Orange Banana Kiwi''' v = 'Apple' " Orange" ''' Banana''' """ Kiwi""" print(v) # Apple Orange Banana Kiwi 
Enter fullscreen mode Exit fullscreen mode
v = '''Apple Orange Banana Kiwi''' print(v) # Apple # Orange # Banana # Kiwi 
Enter fullscreen mode Exit fullscreen mode
v = """ Apple Orange Banana Kiwi """ print(v) # # Apple # Orange # Banana # Kiwi # 
Enter fullscreen mode Exit fullscreen mode

A string can be iterated with a for statement as shown below:

for v in 'ABC': print(v) # A # B # C 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode
v1, *v2, v3 = 'ABCDEF' print(v1, v2, v3) # A ['B', 'C', 'D', 'E'] F print(v1, *v2, v3) # A B C D E F 
Enter fullscreen mode Exit fullscreen mode
for v1, v2, v3 in ['ABC', 'DEF']: print(v1, v2, v3) # A B C # D E F 
Enter fullscreen mode Exit fullscreen mode
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 
Enter fullscreen mode Exit fullscreen mode
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 
Enter fullscreen mode Exit fullscreen mode
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] 
Enter fullscreen mode Exit fullscreen mode
print([*'ABC', *'DE']) # ['A', 'B', 'C', 'D', 'E'] 
Enter fullscreen mode Exit fullscreen mode
print(*'ABC', *'DE') # A B C D E 
Enter fullscreen mode Exit fullscreen mode
print(**'ABCDE') # TypeError: print() argument after ** must be a mapping, not str 
Enter fullscreen mode Exit fullscreen mode

An empty string is False as shown below:

print(bool('')) # Empty str # False  print(bool(' ')) # str # True 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode
v = 'ABCD' print('B' not in v) # False  print('CD' not in v) # False  print('b' not in v) # True 
Enter fullscreen mode Exit fullscreen mode

A string can be enlarged with * and a number as shown below:

v = 'ABC' * 3 print(v) # ABCABCABC 
Enter fullscreen mode Exit fullscreen mode
v = '012' * 3 print(v) # 012012012 
Enter fullscreen mode Exit fullscreen mode
v = '' * 3 print(v) # Nothing 
Enter fullscreen mode Exit fullscreen mode

Be careful, a huge string gets I/O error as shown below:

v = 'ABC' * 100000000 print(v) # OSError: [Errno 29] I/O error 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode
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 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode
v = 'abcdef' del v[0], v[3:5] # TypeError: 'str' object does not support item deletion 
Enter fullscreen mode Exit fullscreen mode
v = 'abcdef' del v print(v) # NameError: name 'v' is not defined 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode
v = 'abcdef' v = list(v) del v[0], v[3:5] v = ''.join(v) print(v) # bcd 
Enter fullscreen mode Exit fullscreen mode

The variables v1 and v2 always refer to the same string because a string cannot be copied as shown below:

*Memo:

  • is keyword or is and not keyword can check if v1 and v2 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 while copy.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 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)