brief introduction
Python Its main application is scientific calculation , The foundation of scientific calculation is numbers , Strings and lists . This article will introduce the usage of these three data types in detail .
Numbers
Numbers are a very important type in any scientific calculation , stay Python The most common type of number in is int and float.
Look at a few basic number operations :
In [8]: 1+1
Out[8]: 2
In [9]: 3*2 + 10
Out[9]: 16
In [10]: (65 + 23) / 4
Out[10]: 22.0
Copy code
We can see it up here , There are no decimals int type , With decimals is float type .
Division operations (/
) Always return floating point type . If you want to do it floor division Get an integer result ( Ignore the decimal part ) You can use //
Operator ; If you want to calculate the remainder , have access to %
In [11]: 54 / 4
Out[11]: 13.5
In [12]: 54 // 4
Out[12]: 13
In [13]: 54 % 4
Out[13]: 2
Copy code
** It can be expressed as a power operation :
In [14]: 4 ** 3
Out[14]: 64
Copy code
We can assign numbers to specific variables , And you can use this variable for subsequent operations .
In [15]: a = 12
In [16]: b = 14
In [17]: a * b
Out[17]: 168
Copy code
In an interactive environment ,_ Represents the last output :
In [17]: a * b
Out[17]: 168
In [18]: 100 + _
Out[18]: 268
Copy code
except int and float,Python Other data types are also supported , such as Decimal and Fraction, It even supports plural .
character string
Python There are three representations of strings in , You can use single quotes , Double quotation marks and triple quotation marks .
In [19]: site1 = 'www.flydean.com'
In [20]: site2= "www.flydean.com"
In [21]: site3= """www.flydean.com"""
Copy code
Three quotes are mainly used for cross line output , Carriage returns in a string are automatically included in the string , If you don't want to include , Add a... At the end of the line \
that will do . as follows :
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
Copy code
If you need to escape , You can use backslashes \
In [22]: site4 = "www.\"flydean\".com"
In [23]: site4
Out[23]: 'www."flydean".com'
Copy code
If you don't want to go ahead \
The character of escape into a special character , have access to Original string The way , Add... Before quotation marks r
that will do :
In [24]: print(r"www.\"flydean\".com")
www.\"flydean\".com
Copy code
Strings are passed through + To connect , You can also use * To copy :
In [25]: "www" + "flydean.com"
Out[25]: 'wwwflydean.com'
In [26]: "www.flydean.com" * 3
Out[26]: 'www.flydean.comwww.flydean.comwww.flydean.com'
Copy code
Two or more adjacent string literal ( Quoted character ) Will automatically connect together .
In [27]: "www" "flydean.com"
Out[27]: 'wwwflydean.com'
Copy code
Be careful , The auto connect operation above , It only works for two literal quantities , If it is a variable, an error will be reported .
Strings are treated as arrays of characters , So you can go through string[index] To visit in the form of .
In [28]: site5 = "www.flydean.com"
In [29]: site5[3]
Out[29]: '.'
Copy code
If the index is negative , It's going to start counting from the right :
In [30]: site5[-3]
Out[30]: 'c'
Copy code
because -0 and 0 It's the same , So negative numbers come from -1 At the beginning .
Except index , String also supports section . Index can get a single character , and section You can get substrings :
In [31]: site5[1:5]
Out[31]: 'ww.f'
Copy code
Note that the beginning of the slice is always included in the result , And the end is not included . This makes s[:i] + s[i:]
Always equal to s
In [33]: site5[:4]+site5[4:]
Out[33]: 'www.flydean.com'
Copy code
The index of slices has a default value , The default value for omitting the start index is 0.
If the index exceeds the range of the string, an out of bounds error is sent .
In [34]: site5[100]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-34-fc1f475f725b> in <module>()
----> 1 site5[100]
IndexError: string index out of range
Copy code
however , The out of bounds index in the slice is automatically processed :
In [36]: site5[:100]
Out[36]: 'www.flydean.com'
Copy code
Because strings are immutable , So we can't modify a string in the form of an index :
In [37]: site[2] = "A"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-37-9147d44bd80c> in <module>()
----> 1 site[2] = "A"
TypeError: 'str' object does not support item assignment
Copy code
len Used to count the length of a string :
In [38]: len(site5)
Out[38]: 15
Copy code
String object str
The essence of string is string object str.
May have a look str Basic approach :
In [39]: site5.
capitalize() encode() format() isalpha() islower() istitle() lower() replace() rpartition() splitlines() title()
casefold() endswith() format_map() isdecimal() isnumeric() isupper() lstrip() rfind() rsplit() startswith() translate()
center() expandtabs() index() isdigit() isprintable() join() maketrans() rindex() rstrip() strip() upper()
count() find() isalnum() isidentifier() isspace() ljust() partition() rjust() split() swapcase() zfill()
Copy code
Students who are interested can study it by themselves .
list
A list is a collection of data represented in square brackets . The data in the list can be of multiple data types , But in general , We use the same data type in a list .
In [40]: ages = [ 10, 14, 18, 20 ,25]
In [41]: ages
Out[41]: [10, 14, 18, 20, 25]
Copy code
Just like a string , Lists also support indexing and slicing . in fact , As long as it is sequence Type of data type , Both support indexing and slicing .
In [42]: ages[3]
Out[42]: 20
In [43]: ages[:2]
Out[43]: [10, 14]
In [44]: ages[:]
Out[44]: [10, 14, 18, 20, 25]
Copy code
Be careful , A slice of the list returns a new list . But this new list is a shallow copy , It means that the elements in the new list are references to the elements in the original list .
The list also supports splicing operations :
In [45]: ages + [9, 11]
Out[45]: [10, 14, 18, 20, 25, 9, 11]
Copy code
and String The immutability is different , The list is variable , This means that we can modify the value of the list through the index :
In [46]: ages[0] = 100
In [47]: ages
Out[47]: [100, 14, 18, 20, 25]
Copy code
The underlying type of the list is list, We can look at it list The method in :
In [51]: ages.
append() count() insert() reverse()
clear() extend() pop() sort()
copy() index() remove()
Copy code
We can use append To attach list Value , You can also use count To statistics list And so on .
We mentioned above , A slice of a list is a reference to the original list , So we can assign values to slices , To modify the values of the original list :
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
Copy code
Lists can also be nested , Build multi tier lists :
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
Copy code
This article has been included in www.flydean.com/03-python-n…
The most popular interpretation , The deepest dry goods , The most concise tutorial , There are so many tricks you don't know about waiting for you to discover !
Welcome to my official account. :「 Program those things 」, Know technology , Know you better !