Foundation of Python: number string and list

flydean 2021-02-23 01:55:51
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

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

** It can be expressed as a power operation :

In [14]: 4 ** 3
Out[14]: 64

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

In an interactive environment ,_ Represents the last output :

In [17]: a * b
Out[17]: 168
In [18]: 100 + _
Out[18]: 268

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"""

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
""")

If you need to escape , You can use backslashes \

In [22]: site4 = "www.\"flydean\".com"
In [23]: site4
Out[23]: 'www."flydean".com'

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

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'

Two or more adjacent string literal ( Quoted character ) Will automatically connect together .

In [27]: "www" "flydean.com"
Out[27]: 'wwwflydean.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 [28]: site5 = "www.flydean.com"
In [29]: site5[3]
Out[29]: '.'

If the index is negative , It's going to start counting from the right :

In [30]: site5[-3]
Out[30]: 'c'

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'

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'

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

however , The out of bounds index in the slice is automatically processed :

In [36]: site5[:100]
Out[36]: 'www.flydean.com'

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

len Used to count the length of a string :

In [38]: len(site5)
Out[38]: 15

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()

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]

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]

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]

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]

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()

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
[]

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'

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 !

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

  1. Python 空间绘图 - 房价气泡图绘制
  2. Translation: practical Python Programming 02_ 02_ Containers
  3. Research on Portfolio Optimization Based on particle swarm optimization
  4. Ubuntu deploying Django project
  5. Two years of Java, write Python and go without byte beating
  6. Translation: practical Python Programming 02_ 02_ Containers
  7. So learn python, grandfather learned! Introduction to super simple Python
  8. python3 多线程 与 mongo亿级消费日志数据 新鲜demo 【优化第一版】
  9. Summary of Chinese word segmentation based on Jieba
  10. I've heard it n times, but I'm not impressed. After reading this, you'll understand
  11. Summary of Chinese word segmentation based on Jieba
  12. From movie art to Python code to realize God's reverse thinking mode
  13. Summary of Chinese word segmentation based on Jieba
  14. ARIMA模型预测CO2浓度时间序列-python实现
  15. Python belongs to back-end development or front-end development? Introduction to Python!
  16. python isinstance()
  17. I've heard it n times, but I'm not impressed. After reading this, you'll understand
  18. This article will familiarize you with the transformation process of Python - & gt; cafe - & gt; om model
  19. 如何用Python一键修改上万个文件名
  20. One day quick start to Python
  21. Python 学习笔记: List
  22. 翻译:《实用的Python编程》02_03_Formatting
  23. Is there any age requirement for learning Python? Is 30 OK?
  24. Professor Tsinghua! The most complete Python tutorial in 12 hours (free sharing at the end of the article)
  25. Using Python to develop defi project
  26. Detailed explanation of Python function
  27. Python 可变类型作为函数默认参数时的副作用
  28. What do Python engineers do? What's their future?
  29. 这是我见过最好的Python教程:十分钟带你认识Python
  30. Python欢喜冤家:爬虫与反爬虫带着处理方案来给大家拜年了
  31. Python - zip() function
  32. 写Python会遇到如下的错误:ModuleNotFoundError: No module named 'email.mime'; 'email' is not a package
  33. Python类的调用以及私有和公有属性方法的调用
  34. Python类的专有方法
  35. Python基础之:数字字符串和列表
  36. How did Python pioneers evaluate this language on their 30th birthday?
  37. Python基础之:数字字符串和列表
  38. Python基础之:数字字符串和列表
  39. 窥探未来不是梦,python数据分析轻松实现
  40. This article will familiarize you with the transformation process of Python - & gt; cafe - & gt; om model
  41. 阿里、华为Python工程师总结的实用技巧,只有你还没看?
  42. 酸了!看到抖音上Python程序员晒得工资条......
  43. Python基础之:数字字符串和列表
  44. Importing excel into database adaptively by Python
  45. Python安装教程
  46. Python安装教程
  47. From Xiaobai to master, here is a guide to pandas
  48. [Python] drawing method of stem leaf diagram and compound pie diagram
  49. Drawing of Python geoplot spatial kernel density estimation map
  50. Python Seaborn economist's classic chart imitation
  51. Python space drawing - regionmask mask operation example
  52. Python space drawing - cartopy longitude and latitude add
  53. Python pykrige package Kriging interpolation calculation and visual rendering
  54. Python batch resampling, mask, slope extraction
  55. Python - Analysis of reachable circle of multiple traffic modes
  56. Python space drawing bubble drawing
  57. Python 3 multithreading and Mongo 100 million consumption log data fresh demo
  58. ARIMA model for predicting time series of CO2 concentration
  59. python isinstance()
  60. How to modify tens of thousands of file names with one key in Python