Python Tutor: Learn Python, JavaScript, C, C++, and Java programming by visualizing code
futurecoder: Learn to code from scratch
Python Tutorials – Real Python
String Indexing
a = 'Hello world'
b = a[0] # 'H'
c = a[4] # 'o'
d = a[-1] # 'd' (end of string)
d = a[:5] # 'Hello'
e = a[6:] # 'world'
f = a[3:8] # 'lo wo'
g = a[-5:] # 'world'
String operations
# Concatenation (+)
a = 'Hello' + 'World' # 'HelloWorld'
b = 'Say ' + a # 'Say HelloWorld'
# Length (len)
s = 'Hello'
len(s) # 5
# Membership test (`in`, `not in`)
t = 'e' in s # True
f = 'x' in s # False
g = 'hi' not in s # True
# Replication (s * n)
rep = s * 5 # 'HelloHelloHelloHelloHello'
String Mutability
Strings are "immutable" or read-only. Once created, the value can't be changed. All operations and methods that manipulate string data, always create new strings.
String Conversions
str()
>>> def function(data=[]):
... data.append(1)
... return data
...
>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]
>>> id(function())
12516768
>>> id(function())
12516768
>>> id(function())
12516768
# function() 函数在不同函数调用中一直在使用同一个列表对象
# instances 共享了 __dict__ 里面的默认参数,