03. Python in slices and advanced variable

1. Slice

1.1. The method is applicable to slice StringListTuple

  • Slice index value is used to define a range, from a large cut out small string string
  • It is an ordered set of lists and tuples, capable of acquiring data corresponding to the index value
  • A dictionary is an unordered collection of key-value pairs to use to save data

1.2 Demo

  • 2-5, taken from the string position
  • ~ 2 taken from the end of the string
  • 1-5, taken from the start position of the string of
  • Interception complete string
  • From the start position, taken every other character string
  • Start from the index 1, a take every
  • 2, taken from the end of the ~ - 1 string
  • End of the string of two characters taken
  • Reverse string (interview questions)
num_str = "0123456789"

# 1. 截取从 2 ~ 5 位置 的字符串
print(num_str[2:6])

# 2. 截取从 2 ~ `末尾` 的字符串
print(num_str[2:])

# 3. 截取从 `开始` ~ 5 位置 的字符串
print(num_str[:6])

# 4. 截取完整的字符串
print(num_str[:])

# 5. 从开始位置,每隔一个字符截取字符串
print(num_str[::2])

# 6. 从索引 1 开始,每隔一个取一个
print(num_str[1::2])

# 倒序切片
# -1 表示倒数第一个字符
print(num_str[-1])

# 7. 截取从 2 ~ `末尾 - 1` 的字符串
print(num_str[2:-1])

# 8. 截取字符串末尾两个字符
print(num_str[-2:])

# 9. 字符串的逆序(面试题)
print(num_str[::-1])

2. Variable advanced

  • Use id()function you can view the data stored in the variable where the memory address
  • In Python, function arguments / return values ​​are to be transmitted by the reference to the
def test(num):

    print("-" * 50)
    print("%d 在函数内的内存地址是 %x" % (num, id(num)))

    result = 100

    print("返回值 %d 在内存中的地址是 %x" % (result, id(result)))
    print("-" * 50)

    return result


a = 10
print("调用函数前 内存地址是 %x" % id(a))

r = test(a)

print("调用函数后 实参内存地址是 %x" % id(a))
print("调用函数后 返回值内存地址是 %x" % id(r))

Here Insert Picture Description

Published 85 original articles · won praise 12 · views 3758

Guess you like

Origin blog.csdn.net/fanjianhai/article/details/103550708