# Basic data type built-in method

### I. conversion between base numbers

• Example
```'''
Binary to decimal
110
Manual calculation: 1 * (2 * * 2) + 1 * (2 * * 1) + 0 * (2 * * 0) = 6
Computer computing: Print (int ("110, 2))

Octal to decimal
123
Manual calculation: 1 * (8 * * 2) + 2 * (8 * * 1) + 3 * (8 * * 0) = 83
Computer computing: Print (int ("123, 8))

Hex to hex
801
Manual calculation: 8 * (16 * * 2) + 0 * (16 * * 1) + 1 * (16 * * 0) = 2049
Computer computing: Print (int ("801, 16))

Decimal to binary
bin(108)
>>>0b1101100
Decimal to octal
oct(108)
>>>0o154
hex(801)
>>>0x321

'''
```

### Basic data types and built-in methods

• Integer int

Purpose: used to record the integer related status of people's age, mobile phone number, etc

Definition method: age = 18

Commonly used in mathematical calculation

Summary: int of integer type is out of order, immutable, and has a value

• Floating point

Purpose: to record the decimal related status of height, weight, salary, etc

Definition method: height = 1.77

Commonly used in mathematical calculation

Summary: unordered, immutable, one value

• String str

Purpose: to save some descriptive information, personal hobbies, personal profile

Definition method: S1 ='yafeng666 '

It can be expressed in single quotation mark, double quotation mark or triple quotation mark, but cannot be mixed

Summary: ordered, immutable, one value

• The built-in method of string priority

```#1.strip() removes the spaces on the left and right sides of the string, but it can't remove the middle space. That user is too unfriendly
s1 = "***yafeng666***"
s1.strip("*")
print(s1.strip("*"))
>>>yafeng666

#2.split() is used to segment strings. You can specify the separator of segmentation and return a list
s2 = "yafeng|18|male"
s2.split("|")
print(s2.split("|"))
>>>['yafeng', '18', 'male']

#3.len() gets the number of elements in the current data, and the space is also a character
s1 = "***yafeng666***"
print(len(s1))
>>>15

str1 = 'hello python!'
# 4. Value by index (forward, reverse):
# 4.1 forward direction (from left to right)
>>> str1[6]
p
# 4.2 reverse fetching (negative sign means right to left)
>>> str1[-4]
h
# 4.3 for str, the value can only be taken according to the index and cannot be changed
>>> str1[0]='H' # Error TypeError

# 5. Slice (look at the head and ignore the tail, step size)
# 5.1 ignore head and tail: take out all characters with index from 0 to 8
>>> str1[0:9]
hello pyt
# 5.2 step size: 0:9:2, the third parameter 2 represents the step size, it will start from 0 and accumulate one 2 at a time, so the characters of index 0, 2, 4, 6 and 8 will be taken out
>>> str1[0:9:2]
hlopt
# 5.3 reverse sectioning
>>> str1[::-1]  # -1 means right to left
!nohtyp olleh

# 6. Member operations in and not in
# 6.1 int: judge whether hello is in str1
>>> 'hello' in str1
True
# 6.2 not in: judge whether tony is not in str1
>>> 'tony' not in str1
True

# 7. cycle
>>> str5 = 'How are you today?'
>>> for line in str5:  # Extract each character in the string in turn
...     print(line)
...
//this
//day
//you
//good
//Do you
？```
• Methods to master string
```1,strip,lstrip,rstrip
str1 = "***yafeng666***"

>>> str1.strip('*')  # Remove left and right specified characters
'yafeng666'
>>> str1.lstrip('*')  # Remove only the specified characters on the left
yafeng666***
>>> str1.rstrip('*')  # Remove only the specified characters on the right
***yafeng666

2,lower(),upper()

>>> str2 = 'My nAme is yafenG!'

>>> str2.lower()  # Change all English strings to lowercase
my name is yafeng!
>>> str2.upper()  # Capitalize all English strings
MY NAME IS YAFENG!

3,startswith,endswith

>>> str3 = 'yafeng 666'

# Startswitch() determines whether the string starts with the character specified in parentheses, and the result is a Boolean value of True or False
>>> str3.startswith('y')
True
>>> str3.startswith('j')
False
# Endswitch() determines whether the string ends with the character specified in parentheses, and the result is a Boolean value of True or False
>>> str3.endswith('666')
True
>>> str3.endswith('sixsixsix')
False

4,Format output format

# Similar to the usage of% s, the passed in value will correspond to {} one by one according to the location
>>> str4 = 'my name is {}, my age is {}!'.format('yafeng', 18)
>>> str4
my name is yafeng, my age is 18!

# Take the values passed in by format as a list, and then use {index} to get values
>>> str4 = 'my name is {0}, my age is {1}!'.format('yafeng', 18)
>>> str4
my name is yafeng, my age is 18!

>>> str4 = 'my name is {1}, my age is {0}!'.format('yafeng', 18)
>>> str4
my name is 18, my age is yafeng!

>>> str4 = 'my name is {1}, my age is {1}!'.format('yafeng', 18)
>>> str4
my name is 18, my age is 18!

# format parentheses can completely disorganize the order when passing parameters, but they can still pass values for the specified parameters by name. Name = 'yafeng' is passed to {name}
>>> str4 = 'my name is {name}, my age is {age}!'.format(age=18,name='yafeng')
>>> str4
'my name is yafeng, my age is 18!'

>>> str4 = 'my name is {name}{name}{name}, my age is {name}!'.format(name='yafeng', age=18)
>>> str4
'my name is yafengyafengyafeng, my age is yafeng!'

5,split,rsplit

# Split will split the string from left to right, and you can specify the number of times to cut
>>> str5='yafeng:/6/6/6'
>>> str5.split('/',1)
['yafeng', '6/6/6']

# rsplit is just the opposite of split. It cuts from right to left. You can specify the number of cuts
>>> str5='6|6|8'
>>> str5.rsplit('|',1)
['6|6', '8']

6,join

# Take multiple strings from the iteratable object, and then splice them according to the specified separator. The splicing result is string
>>> '%'.join('hello') # Take multiple strings from the string 'hello' and splice them with% as the separator
'h%e%l%l%o'
>>> '|'.join(['yafeng','18','read'])  # Extract multiple strings from the list and splice them with * as a separator

7,replace

# Replace the old character in the string with a new character
>>> str7 = 'my name is yafeng, my age is 18!'  # Change the age of yafeng from 18 to 22
>>> str7 = str7.replace('18', '22')  # Syntax: replace('old content ',' new content ')
>>> str7
my name is yafeng, my age is 22!

# You can specify the number of modifications
>>> str7 = 'my name is yafeng, my age is 18!'
>>> str7 = str7.replace('my', 'MY',1) # Change only one my to my
>>> str7
'MY name is yafeng, my age is 18!'

8,isdigit

# Judge whether the string is composed of pure numbers, and the return result is True or False
>>> str8 = '1314520'
>>> str8.isdigit()
True

>>> str8 = 'yafeng666'
>>> str8.isdigit()
False```
• String knowledge
```# 1.find,rfind,index,rindex,count
# 1.1 find: find the starting index of the substring from the specified range, return the number 1 if found, and - 1 if not found
>>> msg='yafeng say hello'
>>> msg.find('f',1,3)  # Find the index of character o in characters with index 1 and 2 (regardless of the end)
1
# 1.2 index: the same as find, but an error will be reported if it cannot be found
>>> msg.index('n',2,4) # Value error
# 1.3 rfind and rindex: omitted
# 1.4 count: count the number of times a string appears in a large string
>>> msg = "hello everyone"
>>> msg.count('e')  # Count the number of occurrences of string e
4
>>> msg.count('e',1,6)  # Number of occurrences of string e in index 1-5 range
1

# 2.center,ljust,rjust,zfill
>>> name='yafeng'
>>> name.center(30,'-')  # The total width is 30, the string is displayed in the middle, not enough - fill
-------------yafeng-------------
>>> name.ljust(30,'*')  # The total width is 30, the string is aligned to the left, not filled with *
yafeng**************************
>>> name.rjust(30,'*')  # The total width is 30, the string is aligned to the right, not filled with *
**************************yafeng
>>> name.zfill(50)  # The total width is 50, the string is right aligned, not enough to be filled with 0
00000000000000000000000000000000000000000000yafeng

# 3.expandtabs
>>> name = 'yafeng\thello'  # \t for tab
>>> name
yafeng    hello
>>> name.expandtabs(1)  # Modify \ tnumber of spaces represented by tabs
yafeng hello

# 4.captalize,swapcase,title
# 4.1 capitalization
>>> message = 'hello everyone nice to meet you!'
>>> message.capitalize()
Hello everyone nice to meet you!
# 4.2 swapcase: case flip
>>> message1 = 'Hi girl, I want make friends with you!'
>>> message1.swapcase()
hI GIRL, i WANT MAKE FRIENDS WITH YOU!
#4.3 title: capitalize each word
>>> msg = 'dear my friend i miss you very much'
>>> msg.title()
Dear My Friend I Miss You Very Much

# 5.is digital series
#In Python 3
num1 = b'4' #bytes
num2 = u'4' #unicode is unicode without u in python3
num3 = 'Four' #Chinese numerals
num4 = 'Ⅳ' #Rome digital

#isdigt:bytes,unicode
>>> num1.isdigit()
True
>>> num2.isdigit()
True
>>> num3.isdigit()
False
>>> num4.isdigit()
False

#Isdecimal: Unicode (no isdecimal method for bytes type)
>>> num2.isdecimal()
True
>>> num3.isdecimal()
False
>>> num4.isdecimal()
False

#IsNumeric: Unicode, Chinese number, Roman number (no IsNumeric method for bytes type)
>>> num2.isnumeric()
True
>>> num3.isnumeric()
True
>>> num4.isnumeric()
True

# Three cannot judge floating point
>>> num5 = '4.3'
>>> num5.isdigit()
False
>>> num5.isdecimal()
False
>>> num5.isnumeric()
False

'''
//Conclusion:
//The most commonly used is isdigit, which can judge the types of bytes and unicode, which is also the most common digital application scenario
//If you want to judge Chinese numbers or roman numbers, you need to use isnumeric.
'''

# 6.is other
>>> name = 'yafeng123'
>>> name.isalnum() #Strings can contain either numbers or letters
True
>>> name.isalpha() #String contains only letters
False
>>> name.isidentifier()
True
>>> name.islower()  # Whether the string is pure lowercase
True
>>> name.isupper()  # Whether the string is pure uppercase
False
>>> name.isspace()  # Whether the string is full of spaces
False
>>> name.istitle()  # Whether the initial letters of words in the string are all uppercase
False```
• list

Definition: separate multiple values of any data type with commas within []

l1 = [1,'a',[1,2]] (essence: l1 = list([1,'a',[1,2]])

• List priority knowledge

```# 1. Value by index memory (forward access + reverse access): can be saved or retrieved
# 1.1 forward direction (from left to right)
>>> my_friends=['yafeng','jason','tom',4,5]
>>> my_friends[0]
yafeng
# 1.2 reverse access (negative sign means right to left)
>>> my_friends[-1]
5
# 1.3 for list, the value of specified location can be modified according to index or index. However, if index does not exist, an error will be reported
>>> my_friends = ['yafeng','jack','jason',4,5]
>>> my_friends[1] = 'martthow'
>>> my_friends
['yafeng', 'martthow', 'jason', 4, 5]

# 2. Slice (look at the head and ignore the tail, step size)
# 2.1 take care of the head and ignore the tail: take out the elements with an index of 0 to 3
>>> my_friends[0:4]
['yafeng', 'jason', 'tom', 4]
# 2.2 step size: 0:4:2. The third parameter 2 represents step size. It will start from 0 and accumulate one 2 at a time, so the elements of index 0 and 2 will be taken out
>>> my_friends[0:4:2]
['yafeng', 'tom']

# 3. length
>>> len(my_friends)
5

# 4. Member operations in and not in
>>> 'yafeng' in my_friends
True
>>> 'xxx' not in my_friends
True

# 5.1 append() append elements at the end of the list
>>> l1 = ['a','b','c']
>>> l1.append('d')
>>> l1
['a', 'b', 'c', 'd']

# 5.2 extend() adds multiple elements at the end of the list at one time
>>> l1.extend(['a','b','c'])
>>> l1
['a', 'b', 'c', 'd', 'a', 'b', 'c']

# 5.3 insert() inserts an element at a specified location
>>> l1.insert(0,"first")  # 0 indicates interpolation by index position
>>> l1
['first', 'a', 'b', 'c', 'alisa', 'a', 'b', 'c']

# 6. delete
# 6.1 del
>>> l = [11,22,33,44]
>>> del l[2]  # Delete element with index 2
>>> l
[11,22,44]

# 6.2 pop() deletes the last element of the list by default and returns the deleted value. You can specify the deleted element by adding index value in parentheses
>>> l = [11,22,33,22,44]
>>> res=l.pop()
>>> res
44
>>> res=l.pop(1)
>>> res
22

# 6.3 remove() indicates which element to delete with the name in parentheses. There is no return value
>>> l = [11,22,33,22,44]
>>> res=l.remove(22) # Find the element to be deleted in the first bracket from left to right
>>> print(res)
None

```

Tags: Python Mobile

Posted on Tue, 05 Nov 2019 05:00:48 -0500 by milsaw