Detailed notes day03 string

Detailed notes day03 string

Today Executive Summary

  1. Detailed strings

    1. Integer
    2. Hexadecimal conversion
    3. index
    4. slice
    5. Steps
    6. String methods

Yesterday Recap

  1. while loop

    • The basic structure of the while loop:

      while 条件:
      缩进 循环体
    • break: Terminator Cycle

    • continue: out of the current cycle, the start of the next cycle

    • Cycles may be controlled by the conditions

    • while else, while when the condition is not satisfied, the execution code in the else

  2. format

    • Format% basic structure:

      a = '内容'
      b = "代码%s这样格式化" % a
    • % Placeholder format:

      • %s: String
      • %d| %i: Integer
      • %%: Escape, it can indicate a print %.
    • f-string string basic structure:

      c = '这样就能{input('请输入内容:')}格式化了'
  3. Operators

    • Comparison operators:< > <= >= == !=
    • Arithmetic operators:+ - * / // % **
    • Assignment operator:= += -= *= /= //= **= %=
    • Logical Operators:and or not
    • Member operator:in not in
  4. Coding acquaintance

    • ascii: support letters, numbers and symbols, does not support Chinese
    • gbk:
      • It contains ascii code
      • An English one byte
      • Chinese a 2 bytes
    • unicode:
      • A 4-byte English
      • A Chinese 4 bytes
    • utf-8:
      • English: 1 byte
      • Europe: 2 bytes
      • Asia: 3 bytes

Today's detailed content

Integer

Integer Data Overview

Integer numbers are Python keywords int, plastic is used in a computer calculation and comparison.

Int 32-bit machine in the range of: -2**31 ~ 2**31-1, namely -2147483648~2147483647;

Int 64-bit machine in the range of: -2**63 ~ 2**63-1, namely -9223372036854775808~9223372036854775807;

In Python 3, the use of all integers int. In In Python 2, smaller shaping function is also used int, but for large integer values is required long.

In In Python 2, the larger value will be a function of shaping the end of Lidentification, for example 321312321L. In Python 3, no matter how much value will not appear identity.

Base conversion acquaintance

10 is converted to binary decimal

Divisible by 2, to get the remainder, the remainder integration from the bottom up. For example seeking binary number 11:

除数  余数
11  1
5   1
2   0
1   1
0

Thus, the 11binary number is 1011.

Binary to decimal conversion

From right to left, each of the weights are 2**(位数 - 1). The median is the order from right to left to count. For example, the penultimate one of the weights are 2**0, namely 1, the right to the penultimate position of the weight 2**1, that is 2. To convert binary to decimal value of each bit binary multiplied only need to change the weight and then they want to add to together. For example, we can calculate the number of such binary 1011decimal value of:

1 * 2 ** 0 + 1 * 2 ** 1 + 0 * 2 ** 2 + 1 * 2 ** 3
= 1 + 2 + 0 + 8
= 11
Hex conversion with Python
  • bin(<十进制数>): Converting the decimal number to a binary (common)
  • int("字符串", 2): The one decimal (for example binary) to decimal

Examples are as follows:

>>> bin(11)
'0b1011'
>>> int('1011', 2)
11

Integer (Digital) summary

  • Integer data type is immutable

  • Can be modified in situ called variable data type, it can not be modified in situ immutable data types, called

    We can use id()to view the data memory address, for example:

    a = 10    # 1428849040
    # id  -- 查看空间内存地址
    print(id(a))
    a = a + 1  # 1428849072
    print(id(a))

    Once the data is modified, the memory address changes.

Index (subscript)

Index, also known as index, used to indicate the location iterables of an element.

  • Index value with a positive integer, from left to right positioning, counting from 0, such as 0,1,2
  • A negative value represented by an integer index, right to left orientation, counting from -1 as -1, -2, -2

E.g:

name = "meet" # 计算机从0开始数
        #0123 (索引值|下标值) 从左向右
        #-4-3-2-1           从右向左

print(name[2]) # 通过索引准确定位内容
print(name[-4]) # 通过索引准确定位内容

输出的结果为:e,m

slice

There is such a string: meet_alex_wusirwe want them to alexget out, how to do it? One possible method is to, respectively a, l, eand xthe index value, they were taken out, and then use the string 加和operation splicing them good, like this:

name = "meet_alex_wusir"
a = name[5] # 取出a
b = name[6] # 取出l
c = name[7] # 取出e
d = name[8] # 取出x
print(a+b+c+d) # 拼接并打印字符串

Of course, also be removed by a method corresponding character cycle, and then spliced ​​into a new string:

name = "meet_alex_wusir"
i = 5
s = ''
while i <= 8:
    s += name[i]
    i += 1
print(s)

Because such cycles are very commonly used in Python, it is encapsulated into a simple way, is a string 切片. The basic format and usage of the following sections:

name = "meet_alex_wusir"
      # 0123456789
print(name[5:9])  # [起始位置:终止位置]  顾头不顾腚(起始位置保留,终止位置不保留)
print(name[-5:])  # [起始位置:终止位置(默认到结尾)]  顾头不顾腚
print(name[:])  # [起始位置(默认从开头):终止位置(默认到结尾)]  顾头不顾腚

输出的结果为:
alex
wusir
meet_alex_wusir

Sometimes we do not want to take the characters one by one, but to get a across a character. For example, for the above "meet_alex_wusirexample, we want to take the first 3, 5, 7bit e, _, l, how does it work?

We can still use the most primitive, respectively, values, and then splicing method string:

name = "meet_alex_wusir"
a = name[2]
b = name[4]
c = name[6]
print(a+b+c)

This approach can really get the results we want, but it is too cumbersome. If we want to deal with a long string, it will be very troublesome. This requires us to introduce when the slice 步长variable. 步长Slicing method using the third parameter, the default value 1. For the above example, we can set 步长as 2:

name = "meet_alex_wusir"
       #0123456789
       #-6-5-4-3-2-1
print(name[2:7:2])  #[起始位置:终止位置:步长(默认为1)]

If we take the steps set to -1 can be achieved from right to left to find:

name = "meet_alex_wusir"
print(name[-1:3:-1])  # 步长可以控制查找方向

输出的结果为:
risuw_xela_

During indexing operations, if the input parameter value exceeds the maximum index, the program will be given. Second during the slicing operation, if the end position exceeds the maximum index value, the program does not complain, but will come to the end of the string:

name = "meet_alex_wusir"
print(name[2:20:2])

输出的结果为:
e_lxwsr

Note that the index can only be sliced ​​and ordered data to use. Integer and Boolean values ​​can not be used for indexing and slicing operations.

Like an integer, a string is immutable Data type:

name = "meet"
print(id(name)) # 2388909933712
name = name + "最帅了"
print(id(name)) # 2388910157296

In Python, an assignment for strings, there will be such an interesting situation:

name = "meet"
name1 = "meet"
print(id(name)) # 2313349022864
print(id(name1)) # 2313349022864

Obviously two assignments, two strings of memory address is actually the same. This is because Python has a small pool of data, small data will reside for some time. If during this time, there is a new assignment to the same data, it will not open up a new memory space, the second is the variable to point to an existing memory address data.

Detailed string method

There are many methods string, the lesson only discuss some common, universal comparison point.

.upper()method

.upper()The method can convert all lowercase string uppercase:

name = "alex"
name1 = name.upper()  # 全部大写
print(name)
print(name1)

输出的结果为:
alex
ALEX

.lower()method

.lower()Method and .upper()Method contrary, is to convert a string in all uppercase to lowercase:

name = "ALEX"
name1 = name.lower()  # 全部小写
print(name)
print(name1)

输出的结果为:
ALEX
alex

.upper()And .lowerthe method is a common scenario is no need to distinguish sensitive some cases, the verification code or user input such as name:

yzm = "0G8k"
my_yzm = input("请输入验证码:[0G8k]")
if yzm.lower() == my_yzm.lower():
    print("ok")
else:
    print("滚")

.startswith()method

.startswith()The method used to determine whether the string starts with the specified arguments, returns a Boolean value:

name = 'alex'
print(name.startswith('a'))

返回的结果是:True

.startswith()The method also supports the string 切片, the string is determined whether or not the slice at the beginning of the respective parameters:

name = 'alex'
print(name.startswith('l', 1, 3))

返回的结果是:True

.endswith()method

.endswith()Usage with startswith()very similar. The difference is, that it is used to determine whether the string ends with the specified character string, returns a Boolean value likewise. .endswith()Methods also support slicing operations.

name = 'alex'
print(name.endswith('x'))

返回的结果是:True

.count()method

.count()The method used to input the number of parameters occurring in the string statistics, for example:

name = "meet_alex"
print(name.count("e"))

返回的结果是:3

.strip()method

Additional knowledge: \nas 换行符, that is, on the keyboard 回车keys; \tas 制表符, that is, on the keyboard Tabkeys:

print("你\n好")  #换行就是键盘上的回车键
print("你\t好")  #制表符就是键盘上的Tab

输出的结果为:
你
好
你   好

.strip()A method for removing spaces across the strings, line breaks and tabs:

name = '   \nalex   \t   '
print(name.strip())

输出的结果为:
alex

.strip()The method can also be specified by the head and tail ends of the removed content setting parameters:

name = 'aaaaa aelx  \naa\ta\naaaaa'
print(name.strip('a'))

输出的结果为:
 aelx  
aa  a

Note that, when the specified parameters are not clear spaces, line breaks and tabs.

.strip()Scenario approach is that when enter the account password, ignore the first space inadvertently entered or copied and pasted it from:

user = input("账号:").strip()
pwd = input("密码:").strip()
if user == "alex" and pwd == "alex123":
    print("ok")
else:
    print("滚")

.split()method

.split()The method used to separate string. According to the default spaces, line breaks and tabs to be divided, the divided spaces, line breaks and tabs will not be present. .split()Method output is a list:

a = "alex alex123"
lst = a.split()
print(lst)

输出的结果为:['alex', 'alex123']

Spaces, line breaks and tabs have the same result:

name = "alex\nmeet"
print(name.split())
name = "alex\tmeet"
print(name.split())
name = "alex meet"
print(name.split())

.split()The method can specify parameters, divided by a particular content:

a = "alex:alex123"
lst = a.split(":")
print(lst)

输出的结果同样是:['alex', 'alex123']

.replace()method

.replace()The method can replace a string of old content with new content. .replace()There are three parameters: Parameter 1 is the old value of the parameter to a new value 2, 3 the replacement frequency parameter (default replace all). E.g:

name = 'alexmeet'
name = name.replace('e', 's', 2)
print(name)

输出的结果是:alsxmset

isMethod Series (series determination)

isThere are many series method, used mainly four:

  • name.isalnum(): Is not used to determine the letters, numbers or Chinese, returns a Boolean value
  • name.isalpha(): Used to determine whether a composition or Chinese letters, returns a Boolean value
  • name.isdigit(): Used to determine whether the Arabic numerals, returns a Boolean value. There is a bug Shi, ⑤ will be recognized as Arabic numerals
  • name.isdecimal()Is not used to determine the composition of a decimal, it returns a Boolean value

for loop

And the existence of an infinite loop while循环, the difference is for循环often in the form of limited circulation.

for循环The basic structure is:

for i in XXX:
    循环体

among them,

  • for: Keyword
  • i:variable name
  • in: Keyword
  • xxx: Iterables

Use of existing knowledge, if we want to print each string "alex"in each character, can be used while循环to achieve:

name = 'alex'
count = 0
while count < len(name):
    print(name[count])
    count += 1

Add here a knowledge of the function len()is a common method, it can get passed in the length argument:

>>> name = "alex"
>>> len(name)
4

If you are using for循环, we can more easily achieve the purpose of:

name = "alex"
for i in name: # 每次循环,for都会把取到的元素赋值给i
    print(i) # 打印变量i

Such a look at the following example:

for i in "abcde":
    pass
print(i)

The final print out only one result e. That's because for循环essentially an 赋值operation, each loop iteration is to be an element object 赋值to a variable. When the final cycle, the string "abcde"of the last element "e"is assigned to the variable i. End of the cycle, ihas not been re 赋值. While the printing operation is not in the loop, but does not affect print out the eresults.

Questions:

The following code will print out what kind of result?

num = 5
count = 1
while num:
    for i in "abc":
        print(i + str(count))
    count += 1
    num -= 1

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/11494892.html