Day 6: detailed explanation of data types (integer, string)

Posted by Anxious on Fri, 04 Feb 2022 13:57:11 +0100

December 21, 2021

1, int: integer

1. Decimal of integer

① Binary

Every two into one, consisting of two numbers 0 and 1, starts with 0b or 0b

bin1 = 0b101
print('bin1Value: ', bin1) #Running result: bin1Value:5
bin2 = 0B110
print('bin2Value: ', bin2) #Running result: bin2Value:6

② Octal

Every eight into one, consisting of eight numbers from 0 to 7, starting with 0O or 0O. Note that the first symbol is the number 0 and the second symbol is the uppercase or lowercase letter O.

oct1 = 0o26
print('oct1Value: ', oct1)  #Operation result: oct1Value:22
oct2 = 0O41
print('oct2Value: ', oct2)  #Operation result: oct2Value:33

③ Decimal system

Every decimal one is composed of ten numbers from 0 to 9. Note that integers in decimal form cannot start with 0 unless the value itself is 0.

Int (m): convert m to decimal int type

float(m): convert m to decimal

a = input('11111')
if int (a) == 123:
    pass

pycharm provides three numbers with an underscore: 320_ 789_ seven hundred and seventy-seven

④ Hex

Every f enters one, which is composed of ten numbers 0 ~ 9 and six letters a ~ f (or a ~ F). It starts with 0x or 0x when writing

hex1 = 0x45
hex2 = 0x4Af
print("hex1Value: ", hex1)  #Running result: hex1Value:69
print("hex2Value: ", hex2)  #Running result: hex2Value:1199

2. Conversion between hexadecimals

(1) Convert decimal to other decimal

① decimal to binary

bin(3) #Binary
# '0b11'

② decimal to octal

oct(9) #octal number system
# '0o11'

③ decimal to hexadecimal

hex(17) #hexadecimal
# '0x11'

(2) Convert other base to decimal

Unified use of int('hexadecimal symbol ', hexadecimal Arabic numerals)**

int('0b11',2)
# 3
int('0o11',8)
# 9
int('0x11',16)
# 17

3. Number separator

python provides a number separator to facilitate us to view and express numbers more intuitively.

distance = 595_000_000
print("Distance between earth and Moon:", distance)
#Operation result: distance between earth and Moon: 595000000

4. A method to master (int)

Here, we need to know that int() is to convert the contents in parentheses into int type data.

2, String: string type

1. Convert other data types to character type

Integer, list and dictionary are OK

a = [1, 2, 3]
print(a)
print(type(a))
print(str(a))
print(type(str(a)))
'''Operation results:
[1, 2, 3]
<class 'list'>
[1, 2, 3]
<class 'str'>
'''

b = {'name': 'Zi Shushu'}
print(b)
print(type(b))
print(str(b))
print(type(str(b)))
'''Operation results:
{'name': 'Zi Shushu'}
<class 'dict'>
{'name': 'Zi Shushu'}
<class 'str'>
'''

2. The character type is wrapped in quotation marks

Want quotation marks in the string: single package double or double package single; Use the escape character \ ''

\It can also be used to wrap lines

Strings can be added and multiplied 3

4. Sequence

The so-called sequence refers to a continuous memory space that can store multiple values. These values are arranged in a certain order and can be accessed through the number of the location of each value (called index).

① Sequence index (subscript)

In the sequence, each element has its own number (index). Starting from the starting element, the index value is incremented from 0.

Subscript out of bounds: index out of bounds

② Sequence type: string, list, tuple, set

③ Slicing (secondary focus): common to strings and lists

a [start position: end position: step size]

a [start position] takes an element, character

sname[start : end : step]

**sname: * * indicates the name of the sequence
**Start: * * indicates the start index position of the slice (including this position). This parameter can also be unspecified. It will default to 0, that is, slice from the beginning of the sequence
**End: * * indicates the end index position of the slice (excluding this position). If it is not specified, it defaults to the length of the sequence
**Step: * * indicates that during the slicing process, the elements are taken every few storage locations (including the current location). That is, if the value of step is greater than 1, the elements will be taken in a "skip" manner when slicing to sequence elements. If the value of step is omitted, the last colon can be omitted

a = '123456789'

print(a[0:8])#Get only the previous one at the end position
#Operation result: 12345678

print(a[0:8:2])
#Operation result: 1357

print(a[::2]) # The default is from the beginning to the last
#Operation result: 13579

print(a[:2]) #By default, it starts from the first one and takes the second one
#Operation result: 12

④ Sequences can be added and multiplied

Addition: it connects two sequences, but does not remove duplicate elements

print('I am' + 'Zi Shushu')
print([1, 2, 3] + [3, 9, 10])
'''Operation results:
I'm Zizi Shushu
[1, 2, 3, 3, 9, 10]
'''

Multiplication: multiplying a sequence with the number n will generate a new sequence, and its content is the result of the original sequence being repeated N times

list = ['1'] * 5
print(list)
#Running result: ['1', '1', '1', '1']

⑤ Check whether the element is included in the sequence

In Python, you can use the in keyword to check whether an element is a member of a sequence, and its syntax format is

​ value in sequence
Where value represents the element to be checked and sequence represents the specified sequence

The usage is the same as that of the in keyword, but the function is just the opposite. There is also the not in keyword, which is used to check whether an element is not included in the specified sequence

str = 'I'm Zizi Shushu'
print('I' in str)

#True

print('I' not in str)

#False
  1. Priority operation
str1 = 'hello python!'

# 1. Value by index (forward and reverse):
# 1.1 forward direction (from left to right)
print(str1[6])
#p
# 1.2 reverse direction (negative sign indicates from right to left)
print(str1[-4])
#h
# 1.3 for str, values can only be obtained by index and cannot be changed
str1[0]='H' # Error TypeError


# 2. Slicing (regardless of head and tail, step size)
# 2.1 regardless of head and tail: take out all characters with indexes from 0 to 8
print(str1[0:9])  
#hello pyt
# 2.2 step size: 0:9:2. The third parameter 2 represents the step size. It will start from 0 and accumulate one 2 each time. Therefore, the characters of indexes 0, 2, 4, 6 and 8 will be taken out
print(str1[0:9:2])  
#hlopt 
# 2.3 reverse slicing to reverse the string
print(str1[::-1])  # -1 means taking values from right to left
#!nohtyp olleh

# 3. Length len
# 3.1 get the length of the string, that is, the number of characters. All characters that exist in quotation marks are counted as characters)
print(len(str1)) # Spaces are also characters
#13

# 4. Member operation in and not in    
# 4.1 int: judge whether hello is in str1
print('hello' in str1)  
#True
# 4.2 not in: judge whether tony is not in str1
print('tony' not in str1) 
#True

# 5.strip removes the characters specified at the beginning and end of the string (spaces are removed by default)
# 5.1 characters are not specified in brackets, and the first and last white space characters (spaces, \ n, \ t) are removed by default
str1 = '  life is short!  '
print(str1.strip())  
#life is short!
#5.2 remove only the blank characters on the left
print(str1.lstrip())   
#5.3 remove only white space characters on the right
print(str1.rstrip())  
# 5.4 remove the characters specified in brackets and remove the characters specified at the beginning and end
str2 = '**tony**'  
print(str2.strip('*'))  
# tony

# 6. split
# 6.1 characters are not specified in brackets, and spaces are used as segmentation symbols by default
str3='hello world'
print(str3.split())
#['hello', 'world']
# 6.2 if the separator character is specified in the bracket, the string will be cut according to the character specified in the bracket
str4 = '127.0.0.1'
print(str4.split('.'))  
#['127', '0', '0', '1']  # Note: the result of split cutting is the list data type


# 7. Circulation
str5 = 'How are you today?'
for line in str5:  # Take out each character in the string in turn
   print(line)

#8. Change case
#8.1 change all English characters into lowercase
print(str3.lower())
#8.2 capitalize all English characters
print(str3.upper())

#9. Judge whether the string starts or ends with the character specified in parentheses, and the result is bool value true or False
#9.1 starrswith ()
print(str3.starswith('t'))
#Ture
print(str3.starswith('j'))
#False
#9.2 end switch ()
print(str3.endswith('jam'))
#Ture
print(str3.endswith('tony'))
#False
'''Usage example:
Judge whether a document is a photo
file_path = 'index.jpg'
if print(file_path.endswith(jpg)):
	print('This is a picture')
'''

#10. Take out multiple strings from the iteratable object, and then splice them according to the specified delimiter. The splicing result is a string
print('%'.join('hello'))#Take out multiple strings from the string 'hello', and then splice them according to% as the split symbol
# h%e%l%l%o
print('|',join(['Zi Shushu','like','run'])) # Take out multiple strings from the list, and then splice them according to | as the separator
# She likes running

#11. Replace with new characters
str7 = 'Little lotus just shows its sharp corners, and butterflies have long stood on it'
str7 = str7.replace('butterfly', 'dragonfly')  #Syntax: replace('old character ',' new character ')
print(str7)
#Operation results: Xiaohe just shows sharp corners, and dragonflies have long stood on his head

#12. Judge whether the string is composed of pure numbers, and the return result is true or False
str8 = '222223333'
print(atr8,isdigit())
# Ture
#Life scene: judge the mobile phone number

Focus on int and string types

  1. for loop

​ break,continue,else

Essence: the number of cycles is controlled by the number of iteratable objects; Assign the elements and characters of the iteratable object to the variable x in turn

  1. Detailed explanation of data types

int(): converts other types to decimal integers

float(): convert to decimal

str(): convert to string

  1. Slice of string:

sname[start : end : step]

sname: indicates the name of the sequence
Start: indicates the start index position of the slice (including this position). This parameter can also be unspecified. It will default to 0, that is, slice from the beginning of the sequence
End: indicates the end index position of the slice (excluding this position). If it is not specified, it defaults to the length of the sequence
Step: means that during the slicing process, the elements are taken every few storage locations (including the current location). That is, if the value of step is greater than 1, the elements will be taken in a "jump" manner when slicing to sequence elements. If the colon of. Step is omitted, the last one can be set

  1. Remove the designated symbols on the left and right

print (a.strip()): remove the spaces on the left and right sides

print (a.strip('*'): remove the specified characters on the left and right sides

print (a.split('specified character '): cut according to the specified character

print(len(a)): get the length

print('1 'in' 123 '): judge whether it contains

That is, slice from the beginning of the sequence

End: indicates the end index position of the slice (excluding this position). If it is not specified, it defaults to the length of the sequence
Step: means that during the slicing process, the elements are taken every few storage locations (including the current location). That is, if the value of step is greater than 1, the elements will be taken in a "jump" manner when slicing to sequence elements. If the value of step is omitted, the last colon can be omitted

  1. Remove the designated symbols on the left and right

print (a.strip()): remove the spaces on the left and right sides

print (a.strip('*'): remove the specified characters on the left and right sides

print (a.split('specified character '): cut according to the specified character

print(len(a)): get the length

print('1 'in' 123 '): judge whether it contains

--------
explain:
1. This column is a study note for you to follow the original article of the [python road] column of CSDN blogger "Lao Yang plays python". Its content is similar to the article of CSDN blogger "Lao Yang plays python". You can click the original link to view it.
Column link: https://blog.csdn.net/weixin_43079274/category_10836520.html?spm=1001.2014.3001.5482
2. If you have any questions about your study notes, please leave a message in the message area or send me a private letter.

Topics: Python Back-end