又是很水的一上午,不过也学习到了一些新知识,好比st.isnum、st.isalpha等等html
来来总结一波:python
今天讲的有:进制转换、str字符串函数的用法:切片、replace、split、isalpha、strip、count、join。面试
差很少就这些了,学就完事了,总结那是必须的。函数
经常使用的就是10进制、2进制(binary)、8进制(octonary)、16进制(hexadecimal),他们以前的转换是须要掌握的。学习
主要就是这三个内置函数:bin、oct、hex,其分别是2进制、8进制、16进制的英文缩写,具体可看上面。code
tmp = 5
htm
print(bin(tmp)) # 0b101
ip
print(oct(tmp)) # 0o5
ci
print(hex(tmp)) # 0x5
字符串
print(tmp.bit_length()) # 3 对应二进制:0b101正好是3位
主要用到 int(str, num)
函数进行互转,具体用法见下方。
print(int("0b101", 2)) # 5
print(int("0o17", 8)) # 15
print(int("0x14", 16)) # 20
print(bin(int("0o17", 8))) # 0b1111
下面介绍的都是字符串的种种操做方法,记住便可。
直接看例子吧,三种用法都有。
st = "thepathofpython"
print(st[0:3]) # the 区间包前不包后
print(st[0:8:3]) # tph 最后面的一个参数是步长
print(st[-6:]) # python 右区间若无值,则默认包括末尾 到底
print(st[-6::-2]) # potph 步长为负数 表示从右到左扫
print(st[-6::2]) # pto 步长为正数 表示从左到右扫
print(st[::-1]) # nohtypfohtapeht 左区间若无值,则默认从首位开始
将字符串中的全部字母转成大写或者小写,upper和lower函数
tmp = "xiYuanGongZi"
print(tmp.upper()) # XIYUANGONGZI
print(tmp.lower()) # xiyuangongzi
判断字符串开头和尾端是否等于某一字符串。
tmp = "thepathofpython"
print(tmp.startswith('the')) # True
print(tmp.startswith('zhe')) # False
print(tmp.endswith("python")) # True
tmp.replace(old, new, count)
替换一些特定的字符串,少许推荐。如有大量的字符要替换,推荐使用re
正则,后面会有介绍。
replace函数用法例子:
tmp = "thepathofthepython"
print(tmp.replace("the", "study")) # studypathofstudypython
print(tmp.replace("the", "study", 1)) # studypathofthepython 第三个count 限制替换的old的次数
st.strip()
st.strip("name")
st.lstrip()
st.rstrip()
默认去除字符串两端的空白字符如:空格、制表符t、换行符n。固然你也能够设置自定义的字符。
strip例子:
tmp = "n tthepathoftpythonnt"
print(tmp.strip()) # thepathof python
tmp2 = "tthepathoftpython"
print(tmp2.strip("thpen")) # athof pytho
print(tmp2.lstrip("thpen")) # athof python 从首端扫描
print(tmp2.rstrip("thpen")) # tthepathof pytho 从未端扫描
st.split(char, count)
,split函数用于分割字符串 ,变成列表.
split用法例子:
tmp = "thepathofpython"
print(tmp.split("*")) # ['', 'the', 'path', 'of', 'python']
print(tmp.split("", 3)) # ['', 'the', 'path', 'ofpython'] 第二个参数count,限制分割的数量å
join函数语法:
str.join(sequence)
这个函数简直就是split函数的cp,一个分割,一个合并。
join函数例子:
tmp = ['', 'the', 'path', 'of', 'python']
print("".join(tmp)) # thepathof*python
和C++中的用法差很少,连函数名称都同样,果真同宗生😂。
str.isalpha() # 字符串的全部字符是否都是字母
str.isalnum() # 字符串的全部字符是否都是字母或数字
str.isdecimal() # 字符串的全部字符是否都是十进制数字
例子:
tmp = "zan66"
tmp2 = "zan"
tmp3 = "666"
print(tmp.isalnum()) # True 字符串的全部字符是否都是字母或数字
print(tmp2.isalpha()) # True 字符串的全部字符是否都是字母
print(tmp3.isdecimal()) # True 字符串的全部字符是否都是十进制数字
主要与统计某个字符在字符串中出现的次数。
count函数例子:
tmp = "thepathofpython"
print(tmp.count("t")) # 3
print(tmp.count("z")) # 0
通常用于列表中,判断某成员是否在列表中。
例子:
tmp = ['the', 'path', 'of', 'python']
print('python' in tmp) # True
print('love' not in tmp) # True
肝的我背疼,歇歇,总算是写完了。原本不想写的,可是必须的坚持,天天一定要完成计划。跟着计划走才会有有进步。
全程手敲,对知识的理解又加深了,明天继续加油。
参考连接: