preface


My journey - is the star journey sea!

How many roads I will walk, how many mountains I will conquer in order to find myself, how many times I will fail, how many times I will start again, and whether it all makes sense, I will wait patiently, I will prepare myself for the journey that leads to my dream and hope. Do not burn yourself out, my stars, wait for me.

Today we are going to talk about how to use the basic data types in Python.

For more information on installation and sinification, see this post from the bloggerDownload and Install VsCodeAs well asPython series: windows10 to configure Python3.0 development environment!Restart VsCode after installation!

In understanding the basic data types, we need to understand what are the basic data types? digitalintAnd Boolean valuebool, string,strList,list, tuples,tupleAnd dictionaries,dictEtc., including their basic usage and its common methods, here will be listed one by one for reference. Then we need to understand some operators, because these basic data types are often used for operations and so on.


On! Basic data type

1, Numbers –>int

Of course, the Python numeric types include int, long, float, complex, and booleans (0 and 1). This section only covers int.

inPython2In, the size of the integer is limited, that is, when the number exceeds a certain range no longerintType, butlongLong integer, while inPython3, all integers are referred to as integer int regardless of their size and length.

The main methods are as follows:

int–> Convert the string data type tointType, note: The contents of a string must be numeric

s = '123'
i = int( s )
print( i)
Copy the code

bit_length()–> Converts a number to binary and returns the minimum number of bits in binary

I =123 print(i.bit_length()) #Copy the code

2, Boolean value –>bool

For booleans, there are only two results True and False, which correspond to the 0 and 1 in binary, respectively. There are so many True (True) values that we just need to know what false (Flase) values are — “None, empty ([]/() /” “/{}), 0;

"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. The following results are false, None, 'and [], (), {}, and 0 > > > bool (None) False > > > bool ('') False > > > bool ([]) False > > > bool (0) False > > > bool (()) False >>> bool({}) FalseCopy the code

3, string –>str

Strings are the most common data type in Python, and can be used for many purposes. You can create strings using single quotes or double quotes.

The string is not modifiable. All about characters we can introduce strings from the aspects of indexing, slicing, length, traversal, deleting, splitting, clearing white space, case conversion, deciding what to start with, and so on.

Create a string

@param: @return: "name ='mr_chen' print(name)Copy the code
slice

> > > name = "mr_chen" > > > name [1] 'I "> > > name [0: - 2] # from the first to the last but one, does not contain the penultimate' mr_ch 'Copy the code
The index — — >The index (), the find ()
"" @name: Sunny Chen @test: test font @msg: this is created by Sunny Chen. '' name = "mr_chen" #index--> Print (name.index("l",2)) #find --> Print (name.find("l",2))Copy the code

The difference between index() and find() is that if the index character or sequence is not in a string, for index– ValueError: substring not found, and for find –> return -1.

>>> name = "mr_chen" >>> print(name.index("q",2)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Substring not found print(name.find("s",2)) #find-- "output: >>> -1Copy the code
Length – >len()
Print (len(name)) # print(len(name)Copy the code

Note: the len() method –> can also be used for other data types, such as seeing the number of elements in lists, tuples, and dictionaries.

Delete – >del
Name ="mr-chen" >>> del name >>> name Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'name' is not definedCopy the code
Determine string contents –>Isalnum (), isalpha(), isDigit ()
# to judge whether the whole for the digital > > > a = "123" > > > Anderson sdigit (True) > > > b = "a123" > > > b.i sdigit # (False) determine whether all letters > > > d = "alx - e" > > > D.isalpha () False >>> c =" Alex ">>> cisalpha () TrueCopy the code
Case conversion –>Capitalize (), lower(), upper(), title(), casefold() capitalize()
# case transform each other > > > name = "Mr - Chen" # capitalize the first letter - > capitalize > > > name. Capitalize () 'Mr Chen - # into title - > title > > > info = "my name is Title () 'My Name Is mr-chen' -->lower >>> Name =" mr-chen" >>> name.lower() 'mr-chen' >>> info.title() 'My Name Is Mr-chen '--> >> Name =" mr-chen" >>> name.lower() 'mr-chen' # all to uppercase - > upper > > > name = "Mr - Chen" > > > name. The upper () 'Mr Chen - # case conversion - > swapcase > > > name = "Mr - Chen" > > > name.swapcase() 'MR-CHEN'Copy the code
Judge what to begin and end with –>Startswith (), endswith ()
>>> name ="mr-chen" >>> name.endswith("n") True >>> name.startswith(" Mr ") TrueCopy the code
Extensions — — >expandtabs()
#expandtabs --> Returns the new string generated after the TAB symbol ('\t') in the string is converted to Spaces. Usually used for tabled output info ="name\tage\temail\nmrchen\t22\[email protected]\nsunny\t33\[email protected]" print(info.expandtabs(10)) >>> print(info.expandtabs(10)) name age email mrchen 22\[email protected] sunny 33\[email protected]Copy the code
Format output –>The format (), format_map ()
Split #partition -> split #partition -> split Generate the list > > > name = "mr_chen" > > > name. The partition (" - ") (' mr_chen ', ' ', ') > > > name. The partition (" _ ") (' Mr ', '_', 'Chen ') #split--> split string, and can specify how many times to split, and return list >>> name=" Mr-Chen-hell-baby!" > > > name. The split (" - ") [' Mr ', 'Chen', 'hello,' baby! '] > > > name. The split (" - ", 2) # specified segmentation several times [' Mr ', 'Chen', 'hello - baby!'] > > >Copy the code
Alternative — — >replace
# replace > > > name = "Mr - Chen" > > > name, replace (" h ", "h") # 'Mr Chen - you can also specify parameters, replacing a few > > > name, replace (" m ", "e", 2)' er - Chen '> > >Copy the code
Clear white Space –>Strip (), lstrip(), rstrip()
>>> name =" mr-chen ">>> name =" mr-chen" >>> name =" mr-chen ">>> name =" mr-chen" >>> name. Rstrip () 'mr-chen' >>>Copy the code
Replace — — >Makestran, translate
# to replace one by one > > > a = "WSZGR" > > > b = "I am a Chinese" > > > v = STR. Maketrans (a, b) # create corresponding relation, >>> info ="I'm a Chinese people, WSZGR ">>> info.translate(v) "I'm a Chine is e people, I'm Chinese" >>>Copy the code

4, list –>list class

A list is a set of elements arranged in a specific order. Its elements can be of any data type — numbers, strings, lists, tuples, dictionaries, Booles, and so on — and its elements can be modified.

Its form is:

Names = [' Mr - Chen, "" Sunny", "Alex"] # or names = list ([' Mr Chen, "" Sunny", "Alex"])Copy the code
Index, Slice
Name =["xiaojia","mr-chen","Sunny"] print(name[0:-1]) M1 =name[1:] print(m1) =name['mr-chen', 'Sunny'] m2 =name[:-1] print(m2) # 'Sunny']Copy the code
Append — — >append()
Append () name =["xiaojia","mr-chen","Sunny"] name. Append ("alex") print(name) ['xiaojia',' Mr-chen ','Sunny', 'Alex ']Copy the code
Development – >extend()
Name =["xiaojia"," Mr ","Sunny"] name.extend(["alex","green"]) print(name) ['xiaojia','mr-chen','Sunny', 'Alex ', Name =["xiaojia","mr-chen","Sunny"] name =["xiaojia","mr-chen","Sunny"] print("hello") print(name) 'Mr Chen -', 'Sunny', 'alex', 'green' and 'h', 'e', 'l', 'l', 'o'] # 3, will the dictionary elements added to the list, note: the key of the dictionary. name =["xiaojia","mr-chen","Sunny"] name.extend({"hello":"world"}) print(name)Copy the code

Note: the difference between the extend and append: –> the former is to add elements as a whole, and the latter is to add elements of a data type into a list. Ex. :

# the extend - > extension name = [" xiaojia ", "Mr - Chen", "Sunny"] name. The extend ([" hello ", "world"]) print (name) -->['xiaojia','mr-chen','Sunny', 'hello', 'world'] # append - - > additional name. Append ([" hello ", "world"]) print output for -- -- > (name) [' xiaojia ', 'Mr Chen -', 'Sunny' [' hello ', 'world']]Copy the code
insert()– > insert
Name =["xiaojia","mr-chen","Sunny"] name. Insert (1,"alex") So the second print(name)Copy the code
pop()– > remove
# pop () - take out, Name =["xiaojia","mr-chen","Sunny"] special_name =name.pop(1) print(name) ['xiaojia', 'Sunny'] # mr-chen <class 'STR '>Copy the code
remove()– > remove,del– > delete
Name =["xiaojia","mr-chen","Sunny"] name.remove("xiaojia") print(name) ['mr-chen', 'Sunny'] #name =["xiaojia","mr-chen","Sunny"] #name.remove("xiaojia") del name[1] print(name) # ['xiaojia', 'Sunny']Copy the code
sorted()–> Sort, default positive order, joinreverse =TrueIs in reverse order
# num =[11,55,88,66,35,42] print(sorted(num)) --> sorted(n) --> sorted(n) --> sorted(n # output: [11, 35, 42, 55, 66, 88] # ['Sunny', 'mr-chen', Print (sorted(num,reverse=True))Copy the code

5, tuple –>tuple

A tuple is a list that cannot be modified. The properties are similar to list. They are identified by parentheses instead of square brackets

Print (name[0]) print(name[0])Copy the code

6. Dictionary –>dict

A dictionary is a series of key-value pairs separated by commas, with each key corresponding to a value that can be accessed by using a key. Disorderly.

The definition of a key must be immutable; it can be a number, a string, a tuple, a Boolean, etc.

The definition of a value can be any data type.

Info ={1:"hello world", # key = number :1, # key = tuple: False:{"name":"Sunny"}, "age":22}Copy the code
Traverse — — >Items, keys, values
Info ={"name":"mr-chen", "age":21, "email":"867647213@qq,com"} Print (key) print(info.keys()) Dict_keys ([' name ', 'age' and 'email']) # keys to print (info. The items ()) output for # - > dict_items ([(' name ', 'Mr. Chen -'), (' age, 21), Dict_values (['mr-chen', 21, '867647213@qq,com'])Copy the code

7, set –>setclass

In my opinion, a set is like a basket. You can store things or take things from it, but these things are unordered. It is difficult for you to specify a single thing to take. At the same time, it can filter through certain methods to get the part of things you need. So collections can be created, added, deleted, and relational.

Properties of a set:

  • 1, to heavy

  • 2, disorderly

  • 3. Each element must be of an immutable type (hashable, which can be used as the key of the dictionary).

Create: set, frozenset

#1, create, will be automatically deduplicated, its elements are immutable data types, Test01 ={"zhangsan","lisi","wangwu","lisi",666,("hello","world",),True} # or test02 = set ({" zhangsan ", "lisi", "wangwu," "lisi", 666, (" hello ", "world",), True}) # 2, immutable collections to create - > frozenset () test =frozenset({"zhangsan","lisi","wangwu","lisi",666,("hello","world",),True})Copy the code
Add:The add, update,
>add names ={"zhangsan","lisi","wangwu"} names.add("sunny" } names.update({"alex","sunny"})Copy the code
Delete:Pop, remove, discard
} names.pop() print(names) # select * from names.pop() print(names); ->remove names ={" lisi","wangwu","alex","sunny"} names.remove("lisi") print(names) # } names.discard("hello") print(names) {" hello","lisi","wangwu","alex","sunny"} names.discard("hello") print(names)Copy the code

Relational operations:Intersection | &, and set, difference set - and a job complement ^, issubset, isupperset

  • For example, there are two classes, The English class and the math class. We need to make statistics on the registration of these two classes. For example, the names of students who signed up for both the English class and the math class, etc., then we can apply the relational operation of the set:
} math_c ={"WangWu","LiuDeHua"," Alex"} #1, intersection --> in a and in b Print (english_c & math_c) print(english_c. Intersection (math_c)) {' Alex ', 'Sunny'} -- > # 2, and set in a or b # in statistical signed up for all the students of class two print (english_c | math_c) print (english_c. Union (math_c) # output is: {'Sunny', 'ZhangSan', 'LiuDeHua', 'LiSi', 'Alex', Print (english_c - math_c) print(english_c.difference(math_c)) # Print (english_c ^ math_c) # print(english_c ^ math_c) # print(english_c ^ math_c) # print(english_c ^ math_c)Copy the code
Determine whether the relationship between two sets is a subset or a parent set –>Issubset, isupperset
N ={1,2,4,6,8,10} m ={2,4,6,8} l ={1,2,11} print(n >= m) #print(n issuperset(n)) subset(n <=n) #print(n issuperset(n)) subset(n <=n) #print(n issuperset(n)) subset(n <=n) #print(n issuperset(n)) subset(n <=nCopy the code

🎉 finally

  • For more references, see here:Chen Yongjia’s blog
  • Like the little friend of the blogger can add a concern, point a like oh, continue to update hey hey!