*Memo:
- My post explains a string (1).
- My post explains a string (2).
- My post explains a string (4).
- My post explains str() (1).
- My post explains str() (2).
A string can be enlarged with * and a number as shown below:
v = 'ABCDE' * 3 print(v) # ABCDEABCDEABCDE v = '01234' * 3 print(v) # 012340123401234 v = '' * 3 print(v) # Nothing A string and other strings can be concatenated with + as shown below:
v = 'ABC' + 'DE' + 'FGHI' print(v) # ABCDEFGHI A string and other string cannot return:
- all the characters in them with
'|'(Union: A ∪ B). - their common characters with
'&'(Intersection: A ∩ B). - the characters in the string which aren't in other string with
'-'(Difference: A - B). - the characters in either the string or other string but not both with
'^'(Symmetric Difference: A Δ B).
v = 'AE' | 'ACE' # TypeError: unsupported operand type(s) for |: 'str' and 'str' v = 'ABCD' & 'ACE' # TypeError: unsupported operand type(s) for &: 'str' and 'str' v = 'ABCD' & 'ACE' # TypeError: unsupported operand type(s) for -: 'str' and 'str' v = 'ABCD' ^ 'ACE' # TypeError: unsupported operand type(s) for ^: 'str' and 'str' 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 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) print(*v1, *v2, *v3) # A ['B', 'C', 'D', 'E'] F # A B C D E F # A B C D E F # G ['H', 'I', 'J', 'K'] L # G H I J K L # G H I J K L print(*'ABCD', *'EF') # A B C D E F print([*'ABCD', *'EF']) # ['A', 'B', 'C', 'D', 'E', 'F'] 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] Be careful, a big string gets OverflowError as shown below:
v = 'ABCDE' * 1000000000 print(v) # OverflowError: repeated string is too long
Top comments (0)