Basic data types of python
int
# int # Convert string to number # a='123a' cannot be changed a = "123" b = int(a) print(b) print(type(b)) # check the type of an element # The ascii value is converted here, if it is more than one character, it cannot be converted a = 'b' b = int(b) print(b) # Base conversion, convert to binary, num = "0011" v = int(num, base=2) print(v) # The binary of the current number, represented by at least a few bits age = 10 r = age.bit_length() print(r)
range
# Create consecutive numbers from 7 to 2, subtracting 2, 7, 5, 3 each time v = range(7, 1, -2) # -2 is the step size for i in v: print(i)
Common String Methods
test="hello world"
# replace, replace ("aa", 'b'), replace aa with b, you can add a few replacements at the end # Commonly used join, split, find, strip, upper, lower, replace must be able to
join adds other in each element
test = 'You are the wind and I am the sand' print(test) t = '*' v = t.join(test) print(v) # There is one more space in each
result:
You are the wind and I am the sand --> you *is* the wind*er *I *is* the sand
split split string
# split string # split(self, sep=None, maxsplit=-1) test = "absadfsfff" # Split all, if you add parameters later, it is split several times v2 = test.split('s') # split by s print(v2, type(v2))
result:
['ab', 'adf', 'fff'] <class 'list'>
find finds a substring
# Find the position where the substring appears for the first time, and there is another rfind that searches from the back to the front, and returns -1 if it is not found # find(self, sub, start=None, end=None) test = "hello" v = test.find('lo') print(v)
Result: 3
replace
# The last parameter is the number of replacements # replace(self, old, new, count=None) test = "hello" v = test.replace("ll", 'tt') print(v) # result # hetto
strip removes whitespace, or other characters
lstrip(self, chars=None) # Remove left and right whitespace, including newlines # or remove the specified character test = '\nAlex ' l_v = test.lstrip() r_v = test.rstrip() v = test.strip() print(l_v, r_v, v)
Alex Alex Alex
upper and lower to uppercase or lowercase
test = "hello" v = test.upper() print(v) # all uppercase v = test.lower() print(v) # all lowercase
slice
# Get a certain character in the string, some are sliced test = "abcde" v = test [0] v2 = test[1:2] # exclude 2 v3 = test[:-1] # first after # string length v4 = len (test) # Strings cannot be modified once created, # Once modified or spliced, a new string will be generated (open up a new space), which is true in many languages
Other ways to learn
# # case conversion # test = "hello WORLD" # v = test.swapcase() # print(v).... There are many more, see the source code
#Determine whether the string contains only letters or numbers , #Whether it is letters and Chinese characters , whether it is a number islower is lowercase , # isalnum(), isalpha, isdecimal isdigit isidentifier islower , # isnumeric isprintable isspace istitle isupper