## python 基础 :数值,链表 ,字符串

![image](//upload-images.jianshu.io/upload_images/193358-2a622f13e53924ac.png?imageMogr2/auto-orient/strip|imageView2/2/w/300/format/webp)

很多网站上都有python教程,不一而足 ,本篇教程会结合我在实际开发过程中遇到的问题,总结出很多有意思的小tricks 。我会把你当做python小白来看待,所以不要心急和担心 ,一步步的讨教一下python的招式 。

### 数值

python是一门动态语言,它可以在运行时声明和使用变量,同时它也是一种强类型的语言 ,这一点有别于PHP,python会提供强制类型转换的方法,与java类似 ,但是PHP的话编译器会自动识别你所运用的变量到底是哪种类型。

**注意**:‘123’可以通过int()来转化成123,但是别的非数字字符串就不可

```
更准确来说,它也满足遇强则强的类型强制转换规则 ,最明显的就是在两个数相除的时候。

```

同时python也是支持复数运算的一门语言,虚部由一个后缀"j"或者"J"来表示 。带有非零实部的复数记为"real+imagj",或者通过`complex(real, img)`函数创建。记得以前c++中最经典的一些题目就是重载+运算符 ,使其可以支持复数运算。来看几个例子:

```
>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)

```

假设复数为z ,那么它的实部就为z.real 虚部就为z.imag

```
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

```

**注意**

不能将复数转化成常用的变量类型 。你可以用abs函数取模。

##### trick:

`在shell交互模式下,最近一次的计算结果保存在变量_(下划线)中,这样就可以很方便的进行运算操作。`

### 字符串

python里面有一个string的module ,我们先从最基本的开始讲起 。
想必你对转义字符并不陌生,在python中也保留了这一转义传统,加入你在字符后面打上\ ,说明接下来的字符串是\之前的逻辑后缀:

```
>>>hello = "This is a rather long string containing\n \several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is
\significant."

print hello

```

将得到

```
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.

```

那么很明显,‘\n’就是我们熟悉的换行,\是逻辑继续符号。具体的输出格式你需要根据自己的shell跑跑看。

##### trick:

`如果我们创建一个“行 ”("raw")字符串 ,\ n序列就不会转为换行,源码中的反斜杠和换行符n都会做为字符串中的数据处理`

```
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."

print hello

```

你将得到:

```
This is a rather long string containing\n\
several lines of text much as you would do in C.

```

但是:

```
r allow \t to be interpreted as the two characters \ and t
也就是说:r‘\t’得到的是\\t

```

`如果你还是嫌太麻烦,那么就用三引号(""")来包裹字符串 ,这样的话两个三引号之间不需要进行行尾换行处理 。`

`同时,就像你想的那样,字符串可以相加可以乘以一个数字进行成倍的复制 ,更令人吃惊的时两个字符串的值可以自动的粘黏在一起:`

```
>>>'str''ing'
>>>'string'

```

`但是这个功能仅仅针对字符串常量。`

接下来要讲到的一个字符串的功能跟python中的数组有莫大的关联 ,其实这句话是废话,一般而言字符串也不过就是一个储存在内存中的字符数组,但是我这句话的本意是想表达 ,python的数组,更严格来讲是list,有一个很强大的功能 ,那就是`切片`。

初学者可能还无法领会切片使用的奥义,那么我们来举几个例子你就能体会为什么这个功能是很多人选择python的理由 。

```
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
上图展示了python列表下标的情况,python的list可以进行负索引操作:
>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except the last two
'Hel'

切片操作有一个很有用的不变性:
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

```

所以现在你回头看看你以前熟悉的那些硬语言 ,没有哪一种是可以像这样操作数组或者列表的,这样就给数据结构和算法提供的莫大的方便 。链表的操作跟上述的操作道理是一样的。这里不赘述了。

###### 下面我们来看看string module

在介绍python中的核心概念module之前,相比你们都尝试过import这个功能 ,没错,python的强大之处就在于它的第三方包,这些包在python简洁的基础之上又进行了整理 ,使得语法更加的简单明了 ,更加地人性化 。这里我们以string这个module为例子,介绍一下有关module的使用,希望大家可以举一反三。

无论对于哪一种语言来讲 ,字符串的操作是重中之重,为此大部分语言都将其作为一个单独的类或者包列出来,提供对字符串操作的方法。python也不例外 。

首先打开你的终端(linux用户 ,windows就cmd吧),分别输入以下命令:
1 python
2 import stirng
3 dir(string)
会出现以下一大坨:

```
['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']

```

这些就是string这个module里面所包含的默认属性以及方法(属于类以级别,可按照java中的类方法理解) ,那些奇奇怪怪的下划线看不懂不要紧,下一篇文章我会解释。如果想知道其中某个函数比如find的用法,请在终端这么做:`help(string.find)` ,那么就会出现:

```
Help on function find in module string:

find(s, *args)
find(s, sub [,start [,end]]) -> in

Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.
(END)

```

它会给你一个抽象方法和一个具体方法,如上,星号看不懂也没有关系 ,下章会讲 ,仅仅先当做参数。

```
注意:
在终端中,(END)是高亮的,你阅读完了以后 ,直接按'q',就会返回到>>>提示符,可以继续操作 。不然这个既不想vim也不像emacs的东西会搞得你头大。

```

那么string中常见的几个函数用法给大家列一下 ,具体情况具体help

```
string.atof(s)# Convert to float
string.atoi(s)# Convert to integer
string.atol(s)# Convert to long
string.count(s,pattern)# Count occurrences of pattern in s
string.find(s,pattern)# Find pattern in s
string.split(s, sep)# String a string
string.join(strlist, sep) # Join a list of string
string.replace(s,old,new) # Replace occurrences of old with new

```

`高度预警:`
函数'atoi'可以把string类型变量转化为int类型变量,但是仅限于转数字字符串类型

```
s='string'
s=string.atoi(s)#错误
s = '123'
s=string.atoi(s)#正确
```

 

 

推荐一下我建的python学习交流扣扣qun:850973621,群里有免费的视频教程 ,开发工具、
电子书籍 、项目源码分享。一起交流学习,一起进步!

![QQ截图20201205144328.png](https://upload-images.jianshu.io/upload_images/25205170-288385a32da6ccc4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![QQ截图20201210135017.png](https://upload-images.jianshu.io/upload_images/25205170-72f625288dee4caf.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![QQ截图20201210135040.png](https://upload-images.jianshu.io/upload_images/25205170-8ddbd40a0ec047b5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

 

 

作者:牧师Harray
链接:https://www.jianshu.com/p/34b111bf27ce
来源:简书
著作权归作者所有 。商业转载请联系作者获得授权,非商业转载请注明出处。

文章来源于网络 ,如有侵权请联系站长QQ61910465删除
本文版权归去快排wWw.seogUrublog.com 所有,如有转发请注明来出,竞价开户托管,seo优化请联系qq❉61910465