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 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 : 1+1
Out: 2 In : 3*2 + 10
Out: 16 In : (65 + 23) / 4
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 : 54 / 4
Out: 13.5 In : 54 // 4
Out: 13 In : 54 % 4
** It can be expressed as a power operation ：
In : 4 ** 3
We can assign numbers to specific variables , And you can use this variable for subsequent operations .
In : a = 12 In : b = 14 In : a * b
In an interactive environment ,_ Represents the last output ：
In : a * b
Out: 168 In : 100 + _
except int and float,Python Other data types are also supported , such as Decimal and Fraction, It even supports plural .
Python There are three representations of strings in , You can use single quotes , Double quotation marks and triple quotation marks .
In : site1 = 'www.flydean.com' In : site2= "www.flydean.com" In : site3= """www.flydean.com"""
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 :
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
If you need to escape , You can use backslashes \
In : site4 = "www.\"flydean\".com" In : site4
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 : print(r"www.\"flydean\".com")
Strings are passed through + To connect , You can also use * To copy ：
In : "www" + "flydean.com"
Out: 'wwwflydean.com' In : "www.flydean.com" * 3
Two or more adjacent string literal （ Quoted character ） Will automatically connect together .
In : "www" "flydean.com"
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 : site5 = "www.flydean.com" In : site5
If the index is negative , It's going to start counting from the right ：
In : site5[-3]
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 : site5[1:5]
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
In : site5[:4]+site5[4:]
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 : site5
IndexError Traceback (most recent call last)
<ipython-input-34-fc1f475f725b> in <module>()
----> 1 site5 IndexError: string index out of range
however , The out of bounds index in the slice is automatically processed :
In : site5[:100]
Because strings are immutable , So we can't modify a string in the form of an index ：
In : site = "A"
TypeError Traceback (most recent call last)
<ipython-input-37-9147d44bd80c> in <module>()
----> 1 site = "A" TypeError: 'str' object does not support item assignment
len Used to count the length of a string ：
In : len(site5)
String object str
The essence of string is string object str.
May have a look str Basic approach ：
In : 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()
Students who are interested can study it by themselves .
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 : ages = [ 10, 14, 18, 20 ,25] In : ages
Out: [10, 14, 18, 20, 25]
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 : ages
Out: 20 In : ages[:2]
Out: [10, 14] In : ages[:]
Out: [10, 14, 18, 20, 25]
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 : ages + [9, 11]
Out: [10, 14, 18, 20, 25, 9, 11]
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 : ages = 100 In : ages
Out: [100, 14, 18, 20, 25]
The underlying type of the list is list, We can look at it list The method in ：
In : ages.
append() count() insert() reverse()
clear() extend() pop() sort()
copy() index() remove()
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']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = 
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = 
Lists can also be nested , Build multi tier lists ：
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
[['a', 'b', 'c'], [1, 2, 3]]
['a', 'b', 'c']
This article has been included in http://www.flydean.com/03-python-number-list-string/
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 ！
- Python Basics data type （ character string 、 list 、 Dictionaries 、 Tuples 、 aggregate 、 Pile up 、 Stack 、 Trees ）
Data types have integers . Boolean . character string . list . Dictionaries . Tuples . aggregate . Pile up . Stacks and trees . 1. integer : Integers are numbers Digital representation python2 64 Bit machine , Range -2^63~2^63-1 Beyond the above scope ,python Automatically convert to l ...
- python Basic data types / character string / Tuples / list / Dictionaries
Python data type Numeric type : int integer ,long Long integer ( stay python3.0 There's no distinction between integers and long integers ).float floating-point :complex The plural (python There is a decimal pool :-5--257): Boolean value ...
- python Basics 2 The string of 、 list 、 Dictionaries 、 aggregate
Contents summary : One .python2 or 3 Two . String splicing 3、 ... and . character string Four . list . Yuan Zu 5、 ... and . Dictionaries 6、 ... and . aggregate 7、 ... and . practice One .python2 or python3 At present, most of them use python2.7, Over time ...
- Python The basic chapter ： character string 、 The list of operations
String manipulation Judge whether it is a number string = "200" string.isdigit() >>false To be improved .. The list of operations List is one of the most commonly used data types in the future , ...
- Python Basics （ Numbers , String method ）
Numbers : # Binary to decimal a=' v=int(a,base=2) print(v) Hexadecimal conversion # How many bits does the binary of the current number have at least b=2 v2=b.bit_length() print(v2) Numerical binary ...
- Chapter five ：python The circular structure of the foundation and the list
python The circular structure of the foundation and the list python Basic compiler selection , Loop structure , list Content of this section python IDE The choice of Formatted output of string data type Loop structure list Simple shopping cart writing 1.pyth ...
- 『Python Basics -4』 character string
# 『Python Basics -4』 character string Catalog 1. What is a string 2. Modify string 2.1 Modify the string size 2.2 Merge ( Splicing ) character string 2.3 Use the multiply sign '*' To achieve the superposition effect of strings . 2.4 Add null... To the string ...
- Python String of basic data type
Python String of basic data type One .Python How to create a string stay python A string is formed by wrapping some text in quotation marks ( Quotation marks can be single quotation marks . Double quotes . Single three quotation marks , Double triple quotes , They are exactly the same ) >> ...
- python Basic numbers 、 character string 、 list 、 Tuples 、 Dictionaries
Python Foundation two : 1. Operator : Judge whether something is contained in something : in It's true not in For false (1). Arithmetic operator : Operator describe example + Add Represents the addition of two objects a + b Output results 3 ...
- Python Basic summary （ Strings are often used , Digital type conversion , Basic operators and process control ）
One . String common operations #Python strip() Method is used to remove the characters specified at the beginning and end of a string ( Default is space ) name='*egon**' print(name.strip('*'))# remove name Variables correspond to ...
- UWP&WP8.1 Redraw the picture WriteableBitmap usage Picture turn byte Array ,byte Array to picture
--- Resume content start --- WriteableBitmap yes UWP and WP8.1 Drawing pictures , The most important way to reorganize pictures . The method is simple , Diversity of methods . By looking at the document ,WriteableBitmap The inheritance of is ...
- Linux The performance parameters of the server
Linux The performance parameters of the server One is based on Linux While the server of the operating system is running , It can also represent all kinds of parameter information . Generally speaking, operation and maintenance personnel . System administrators will be extremely sensitive to this data , But these parameters are also very important for developers , ...
- my ElasticSearch Summary of cluster deployment -- Big data search engine you have to know
Abstract : There are three kinds of books in the world :1. Introduce knowledge ,2. Expound theory ,3. Reference book : There are also two kinds of knowledge :1. technology ,2. thought . Here's what I'm deploying ElasticSearch A summary of the experience in clustering , They fall roughly into the first category of knowledge “techknow ...
- [ turn ]Android Use Fragment The interface jumps down and returns one level at a time
1. First, paste the project structure diagram : 2. First add an interface file BackHandledInterface.java, Define a setSelectedFragment Method is used to set the currently loaded Fragment At the top of the stack , Main boundary ...
Reprinted from :http://blog.csdn.net/wang4978/article/details/6721157 <html> <head> <title> Drag the line ...
- Windbg Grab program crash dmp Method of file
Windbg Grab program crash dmp Method of file One . brief introduction windbg Is in windows Under the platform , Powerful user and kernel debugging tools . Compared with Visual Studio, It is a lightweight debugging tool , ...
- net Resume of software engineer
Net Resume of software engineer surname name : Wang Jingjing sex other : Woman Date of birth : 1991-12 cadastral Guan : hebei To live : Beijing learn calendar : Specialty E-mail: 335659753@qq. ...
- LeetCode OJ 98. Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...
- linux Scripts keep logs
Use tee Make the screen and file output log . 2 >&1 in 2 It's error output ,1 It's standard output , 2>&1 It's standard and error output together . repo sync 2>&1 | tee -a ...
- sharepoint REST API Get folders and files
Use REST Operation folder : Get folder url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Shared Documents')/f ...