python学习笔记2

it2022-05-07  38

再次重申学习的是某位THU大神,网址贴下

http://nbviewer.jupyter.org/github/lijin-THU/notes-python/tree/master/

只贴了我不太熟悉的 适合有其他编程语言基础的看

chat 2 part2 some function about number and string

import sys sys.maxint # 求最大int

python使用j开表示复数

a = 1 + 2j type(a) a.real a.imag a.conjugate()

python取整方法

int() # 向下取整 round() # 四舍五入 ceil() # 向上取整

多种进制

1e-6 0xFF 067 # 八进制 0b101010

字符串分割方法

line = "1 2 3 4 5" numbers = line.split() print numbers # 有分割就有合并 s = ' ' s.join(numbers)

字符串替换

s = "hello world" s.replace('world', 'python')

其他字符串操作

s.upper()方法返回一个将s中的字母全部大写的新字符串

s.lower()方法返回一个将s中的字母全部大写的新字符串

s.strip()返回一个将s两端的多余空格除去的新字符串

s.lstrip()返回一个将s开头的多余空格除去的新字符串

s.rstrip()返回一个将s结尾的多余空格除去的新字符串

s = "123 2341" dir(s) # 查看s可以做的操作

当代码太长或者为了美观起见时,我们可以使用两种方法来将一行代码转为多行代码:

()

如下

a = ("hello, world. " "it's a nice day. " "my name is basasuya") a = "hello, world. " \ "it's a nice day. " \ "my name is basasuya"

可以将整数按照不同进制转化为不同类型的字符串

hex(255) oct(255) # 八进制 bin(255) int('23') float('23') int('FF', 16) # 指定原本是什么进制

Python 格式化字符串

'{} {} {}'.format('a', 'b', 'c') '{2} {1} {0}'.format('a', 'b', 'c') # 数字代表在format当中的第几个 '{color} {n} {x}'.format(n=10, x=1.5, color='blue') # 字符相当于map '{0:10} {1:10d} {2:10.2f}'.format('foo', 5, 2 * 3.14) '{0:10} {1:10d} {n:10.2f}'.format('foo', 5, 2 * 3.14, n=12) s = "some numbers:" x = 1.34 y = 2 # 用百分号隔开,括号括起来 t = "%s %f, %d" % (s, x, y)

python中的字符串有一个非常有趣的现象

负数代表的是后面数的字符

s = "hello world" s[-2] # s[11] # 大于长度的字符串却是不行的 s[:] ->'hello world' s[::2] hlowrd # 每隔2个字符取一次

转载于:https://www.cnblogs.com/Basasuya/p/8673410.html


最新回复(0)