Foundation of Python: number string and list

The procedure 2021-02-23 04:00:45
foundation python number string list


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 !

版权声明
本文为[The procedure]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210222221617187c.html

  1. Python 学习笔记: List
  2. 翻译:《实用的Python编程》02_03_Formatting
  3. Is there any age requirement for learning Python? Is 30 OK?
  4. Professor Tsinghua! The most complete Python tutorial in 12 hours (free sharing at the end of the article)
  5. Using Python to develop defi project
  6. Detailed explanation of Python function
  7. Python 可变类型作为函数默认参数时的副作用
  8. What do Python engineers do? What's their future?
  9. 这是我见过最好的Python教程:十分钟带你认识Python
  10. Python欢喜冤家:爬虫与反爬虫带着处理方案来给大家拜年了
  11. Python - zip() function
  12. 写Python会遇到如下的错误:ModuleNotFoundError: No module named 'email.mime'; 'email' is not a package
  13. Python类的调用以及私有和公有属性方法的调用
  14. Python类的专有方法
  15. Python基础之:数字字符串和列表
  16. How did Python pioneers evaluate this language on their 30th birthday?
  17. Python基础之:数字字符串和列表
  18. Python基础之:数字字符串和列表
  19. 窥探未来不是梦,python数据分析轻松实现
  20. This article will familiarize you with the transformation process of Python - & gt; cafe - & gt; om model
  21. 阿里、华为Python工程师总结的实用技巧,只有你还没看?
  22. 酸了!看到抖音上Python程序员晒得工资条......
  23. Python基础之:数字字符串和列表
  24. Importing excel into database adaptively by Python
  25. Python安装教程
  26. Python安装教程
  27. From Xiaobai to master, here is a guide to pandas
  28. [Python] drawing method of stem leaf diagram and compound pie diagram
  29. Drawing of Python geoplot spatial kernel density estimation map
  30. Python Seaborn economist's classic chart imitation
  31. Python space drawing - regionmask mask operation example
  32. Python space drawing - cartopy longitude and latitude add
  33. Python pykrige package Kriging interpolation calculation and visual rendering
  34. Python batch resampling, mask, slope extraction
  35. Python - Analysis of reachable circle of multiple traffic modes
  36. Python space drawing bubble drawing
  37. Python 3 multithreading and Mongo 100 million consumption log data fresh demo
  38. ARIMA model for predicting time series of CO2 concentration
  39. python isinstance()
  40. How to modify tens of thousands of file names with one key in Python
  41. Python notes: List
  42. Translation: practical Python Programming 02_ 03_ Formatting
  43. Python中的四种队列(queue)、堆(heap)
  44. Side effects of Python mutable types as default parameters of functions
  45. This is the best Python tutorial I've ever seen: ten minutes to get to know python
  46. 使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
  47. Python happy enemy: crawler and anti crawler with a solution to give you New Year
  48. 使用python编写量子线路打印的简单项目,并使用Sphinx自动化生成API文档
  49. When writing python, you will encounter the following error: modulenotfounderror: no module named ' email.mime '; 'email' is not a package
  50. Python class call and private and public property method call
  51. Proprietary methods for Python classes
  52. Foundation of Python: number string and list
  53. Foundation of Python: number string and list
  54. Foundation of Python: number string and list
  55. 华为 Python网络自动化
  56. Python Cannot open E:\Python36\Scripts\pip-script.py
  57. Peeping into the future is not a dream, python data analysis is easy to achieve
  58. The practical skills summed up by Alibaba and Huawei Python engineers, only you haven't seen them yet?
  59. Sour! See the Python programmers on the tiktok get the pay slip...
  60. Foundation of Python: number string and list