timerring

Python Basic Data Type

December 21, 2024 · 6 min read · Page View:
Tutorial
Python
If you have any questions, feel free to comment below.

This article will explore data types and common methods for them in Python. The content of this review is as follows: number type, string type, boolean type and type conversion.

CH2 Basic Data Type #

1.Number Type #

Basic Type #

Integer Type #

  • Default is decimal
  • Binary: 0b, Octal: 0o, Hexadecimal: 0x
a = bin(16)   # Binary
b = oct(16)   # Octal
c = hex(16)   # Hexadecimal
print(a, b, c)
# 0b10000 0o20 0x10
# Attention: str type
  • Convert other base to decimal
d = int(a, 2)      # Binary
e = int(b, 8)      # Octal
f = int(c, 16)     # Hexadecimal
print(d, e, f)
# 16 16 16

Float Type #

  • Floating point number
(0.1+0.2) == 0.3
# 0.30000000000000004
# False

Computer uses binary to represent floating point number

  • Reason: Some decimal numbers cannot be represented by binary

      Binary                   Decimal
    

0.00011001100110011001 0.09999942779541016

0.0011001100110011 0.1999969482421875

0.01001100110011001 0.29999542236328125

0.01100110011001101 0.40000152587890625

0.1 === $1*2^{-1}$ === 0.5

  • Usually not affect calculation precision
  • Can use rounding to solve: round(parameter, certain number of decimal places)
a = 3*0.1
print(a)
# 0.30000000000000004
b = round(a, 1)
print(b)
# 0.3
b == 0.3
# True

Complex Type #

# Capital J or lowercase j
3+4j
2+5J
# When the imaginary part coefficient is 1, it needs to be explicitly written
2+1j

Operations #

  • Addition, subtraction, multiplication, division
  • Negation -
  • Exponentiation **
  • Integer quotient //: x/y floor division
  • Modulo operation %: x/y calculate remainder

Integer and floating point number operations result in floating point numbers

The result of division is a floating point number 8/4 = 2.0

Operations Functions #

  • Calculate absolute value abs()
abs(3+4j)  # Calculate the modulus of the complex number a+bj (a^2+b^2)=0.5
# 5.0
  • Power pow(x,n) is equivalent to x**n
  • Power modulo pow(x,n,m) is equivalent to x**n % m
  • Rounding round(x,n) n is the number of decimal places, default is no n, rounding to integer
  • Integer quotient and modulo operation divmod(x,y) is equivalent to returning a tuple (x//y,x % y)
  • Sequence maximum/minimum value max( ) min( )
a = [3, 2, 3, 6, 9, 4, 5]
print("max:", max(a))
print("min:", min(a))
# max: 9
# min: 2
  • Sum sum(x) Note: sum needs to fill in a sequence data
sum((1, 2, 3, 4, 5))
# 15
  • Use scientific calculation library math\scipy\numpy
import math   # Import library
print(math.exp(1))   # Exponential operation e^x
print(math.log2(2))  # Logarithmic operation
print(math.sqrt(4))  # Square root operation  Equivalent to 4^0.5
import numpy as np
a = [1, 2, 3, 4, 5]
print(np.mean(a))    # Calculate mean
print(np.median(a))  # Calculate median
print(np.std(a))     # Calculate standard deviation

2.String Type #

String Expression #

  • Use "" or '' to enclose any character, refer to the situation where the string contains double quotes or single quotes.
  • If you only want to use one, you can use the escape character \ to achieve it.
# print(""Python" is good") # False
print("\"Python\" is good")  # \ character
# "Python" is good
  • The escape character can be used to continue inputting on a new line
s = "py\
thon"                    
print(s)
# python

String Properties #

String Index (Single Character) #

Variable name[position number]

  • Positive index – starts from 0 and increases, spaces are also a position
  • Negative index – starts from -1 and decreases
  • Position number cannot exceed the length of the string
s = "My name is Peppa Pig"
print(s[0])
# M 
print(s[2])
# 
print(s[-1])
# g
print(s[-3])
# P

String Slicing (Multiple Characters) #

Variable name[start position:end position:slice interval]

  • The slice interval defaults to 1, which can be omitted
  • Range: front closed and back open
s = "Python"
print(s[0:3:1]) == print(s[0:3])
# Pyt
print(s[0:3:2])
# Pt
  • The starting position is 0, which can be omitted
  • The end position is omitted, which means it can be taken to the last character
s = "Python"
print(s[0:6]) == print(s[:6]) == print(s[:])
# Python

Reverse Slicing

  • The starting position is -1, which can be omitted
  • The end position is omitted, which means it can be taken to the first character
  • The key point is -1, which means the previous position is -1 larger than the next position
s = "123456789"
print(s[-1:-10:-1])
# 987654321
print(s[:-10:-1])
# 987654321
print(s[::-1])
# 987654321

String Operators #

String Concatenation #

  • String1 + String2

String Multiplication #

  • String * n
c = a+b
print(c*3)
print(3*c)

Member Operation #

  • Subset in full set: Any continuous slice is a subset of the original string
folk_singers = "Peter, Paul and Mary"    
"Peter" in folk_singers
# True
  • Traverse string characters: for character in string
for s in "Python":
    print(s)
# P
# y
# t
# h
# o
# n

String Processing Functions #

String Length #

  • Number of characters len(string)

Character Encoding #

Convert Chinese characters, English letters, numbers, special characters, etc. to computer-recognizable binary numbers

  • Each single character corresponds to a unique, non-repeating binary code
  • Python uses Unicode encoding

ord(character)Convert character to Unicode code

print(ord("1"))
# 49
print(ord("a"))
# 97

chr(Unicode code)Convert Unicode code to character

print(chr(1010))
# ϲ
print(chr(23456))
# 宠

String Processing Methods #

Return a list, the original string remains unchanged

String Splitting .split(" ") #

languages = "Python C C++ Java PHP R"
languages_list = languages.split(" ")# The parameter in the parentheses is the mark we want to split the target string
print(languages_list)
print(languages_list)
# ['Python', 'C', 'C++', 'Java', 'PHP', 'R']
print(languages)
# Python C C++ Java PHP R

String Aggregation ",".join(" ") #

  • Iterable type, such as string, list
s = "12345"
s_join = ",".join(s) # Take out each element of the iterable object, add the aggregation character between the two
s_join
# '1,2,3,4,5'
  • The elements of the sequence type must be of character type
# s = [1, 2, 3, 4, 5] cannot be used for aggregation
s = ["1", "2", "3", "4", "5"]
"*".join(s) 
# '1*2*3*4*5'

Delete specific characters at both ends .strip("delete character") #

  • strip searches from both sides, deletes the specified character when encountered, stops searching when a non-specified character is encountered
  • There are also left deletion lstrip and right deletion rstrip
s = "      I have many blanks     "
print(s.strip(" ")) # Search from both sides, delete spaces after encountering the specified character, then stop
# I have many blanks
print(s.lstrip(" "))
# I have many blanks
print(s.rstrip(" "))
#       I have many blanks

String Replacement .replace("replaced", "replaced with") #

s = "Python is coming"
s1 = s.replace("Python","Py")
print(s1)
# Py is coming

String Count .count("sample string") #

s = "Python is an excellent language"
print("an:", s.count("an"))
# an: 2

String Letter Case and First Letter Capital .upper() .lower() .title() #

s = "Python"
print(s.upper())
# PYTHON
print(s.lower())
# python
print(s.title())
# Python

3.Boolean Type #

Logical Operation Results #

  • any() Data has a non-zero value is True
  • all() Data has a zero value is False (all non-zero)
print(any([False,1,0,None]))   # 0 False None are all zero
# True
print(all([False,1,0,None]))
# False

Mask for numpy array #

import numpy as np
x = np.array([[1, 3, 2, 5, 7]])   # Define numpy array
print(x > 3)
# [[False False False  True  True]]
x[x > 3]
# array([5, 7])

4.Type Identification and Type Conversion #

Type Identification #

type()

age = 20
name = "Ada"
print(type(age))
# <class 'int'>
print(type(name))
# <class 'str'>

isinstance(variable, type) Recognize inheritance

  • The variable type is a subtype of the type, then it is true, otherwise it is false
print(isinstance(age, int))        # Recognize inheritance, here int is equivalent to a class
# True
print(isinstance(age, object)) # object is the ancestor of all classes
# True

String Check Methods #

  • string.isdigit() Character is only composed of numbers
  • string.isalpha() Character is only composed of letters
  • string.isalnum() Character is only composed of numbers and letters

Type Conversion #

  • Number type to string str(number type)
  • String composed of only numbers to number int() float() eval()
s1 = "20"
int(s1)  # 20
s2 = "10.1"
# int(s2) will error
float(s1)
# 20.0
eval(s2)
# 10.1

Related readings


<< prev | Python Basic... Continue strolling Python... | next >>

If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: