python常见内置函数和模块的使用

python常见内置函数和模块的使用




在 python2.x 时 input 默认编码为GBK编码,而Python中字符串编码则使用#coding来指定
常用方式:
#coding=utf-8
#coding:utf-8
#-*-coding:utf-8 - * -

#Python 标准库string 提供了用于字符串格式化的模板类Template
from string import Template
t = Template('My name is ${name}, and is ${age} years old.')
d = {'name':'xie', 'age':21}
print(t.substitute(d))#结果为My name is xie, and is 21 years old.
#字符串常用方法 find(), rfind(),index(),rindex(),count()
s = "apple,peach,banana,peach,pear"
# print(s.find("peach")#返回第一次出现的位置
# print(s.find("peach",7))
#split(),rsplit(),partition(),rpartition()
li = s.split(",")
print(li)#结果为['apple', 'peach', 'banana', 'peach', 'pear']
li_1 = s.rsplit("peach")#结果['apple,', ',banana,', ',pear']
print(li_1)
li_2= s.partition(",")
print(li_2)#返回三部分,分割前的字符串,分割府字符串,分割府后的字符串结果为('apple', ',', 'peach,banana,peach,pear')
li_3 = s.rpartition(",")
print(li_3)#result:('apple,peach,banana,peach', ',', 'pear')
#对于split和rsplit方法,如果不指定分割府,则字符串中的任何空白符号(包括空格,换行符,制表夫)的连续出现都将被分为分割府
s_b = 'hello world \n \n My name is xiexukang \t\t'
print(s_b.split())#result:['hello', 'world', 'My', 'name', 'is', 'xiexukang']



#lower(),upper(),capitalize(),title(),swapcase()
#lower,upper()将字符串转换为小写,大写,
s_temp = "XIEX U KANG"
print(s_temp.title())#result:Xiexukang title()返回的是每个单词首字母大写
print(s_temp.lower())#result:xiexukang
s_temp = "XIEX U KANG"
print(s_temp.capitalize())#resilt:
#swapcase()大小写互换
s_temp = "What is yOu Name"
print(s_temp.swapcase())#result:wHAT IS YoU nAME
#maketrans(),translate()
#maketrans()用来生成字符映射表,而translate()方法则按映射表中定义的对应关系转换字符串并替换其中的字符
table =''.maketrans('abcdef123','uvwxyz@#$')#映射关系
s = "Python is a greate programming language. I like it!"
print(s.translate(table))#result:Python is u gryuty progrumming lunguugy. I liky it!
#use the maketrans and translate() to generate some password
import string
begin = string.ascii_lowercase + string.ascii_uppercase
end = begin[3:10]+begin[:3]+begin[20:]+begin[10:20]
table = ''.maketrans(begin,end)
your_input = "input('input the word to translate:')"
print(your_input.translate(table))

#strip(),rstrip(),lstrip()可以用来删除两端,右端,左端空白字符或指定字符。
s = "abc ww"
print(s.strip())#result:abc ww因为两端不存在空的字符串


#inner function eval() can translate any string to Python expression and cal
print(eval('3+4'))#result:7
a = 3
b =4
c = -2
print(eval('a+b*c'))#result: -5
#in can judge a string have some word
words = ('测试','非法','暴力','花')
text = '这句话要的就是非法和暴力,测试大家的反映速度'
for temp_word in words:
	if temp_word in text:
		text=text.replace(temp_word, '***')#result:这句话要的就是***和***,***大家的反映速度

print(text)
#startswith(),endswith()测试字符串是否以某开头或者结尾可以接收一个字符串元组作为参数来表示前缀或着后缀
if text.startswith(('这句话','非法','暴力')): #result:yes
	print("yes")
#isalnum()测试字符串是否为数字或字母
test_str = "x12"
print(test_str.isalnum())#result:true
#isalpha 是否为字母,isdigit 是否为数字, isspace 是否为空白字符,isupper 是否为大写字符
#islower 是否为小写字符 注意:isnumeric()方法支持汉字数字
#unicodedate提供了不同形式的数字字符到十进制数字的转换方法
import unicodedata
print(unicodedata.numeric('2'))#result:2.0
print(unicodedata.numeric('九'))#result:9.0
#center():居中对齐,ljust():左对齐,rjust():right same location,zfill():返回指定宽度的字符串,在左侧以字符0填充
print('xxk'.center(20, '~'))#reuslt:~~~~~~~~xxk~~~~~~~~~
print('xxk'.ljust(10, '*'))#result:xxk*******
print('xxk'.rjust(10, ')'))#result:)))))))xxk
print('xxk'.zfill(4))#result:0xxk
text_to_format = '''The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!'''
#python 标准库textwrap提供了更加友好的排版函数
import textwrap
print(textwrap.fill(text_to_format,width=80))#按指定矿度进行排序,默认长度最大为70python2.x 时 input 默认编码为GBK编码,而Python中字符串编码则使用#coding来指定
常用方式:
#coding=utf-8
#coding:utf-8
#-*-coding:utf-8 - * -

#Python 标准库string 提供了用于字符串格式化的模板类Template
from string import Template
t = Template('My name is ${name}, and is ${age} years old.')
d = {'name':'xie', 'age':21}
print(t.substitute(d))#结果为My name is xie, and is 21 years old.
#字符串常用方法 find(), rfind(),index(),rindex(),count()
s = "apple,peach,banana,peach,pear"
# print(s.find("peach")#返回第一次出现的位置
# print(s.find("peach",7))
#split(),rsplit(),partition(),rpartition()
li = s.split(",")
print(li)#结果为['apple', 'peach', 'banana', 'peach', 'pear']
li_1 = s.rsplit("peach")#结果['apple,', ',banana,', ',pear']
print(li_1)
li_2= s.partition(",")
print(li_2)#返回三部分,分割前的字符串,分割府字符串,分割府后的字符串结果为('apple', ',', 'peach,banana,peach,pear')
li_3 = s.rpartition(",")
print(li_3)#result:('apple,peach,banana,peach', ',', 'pear')
#对于split和rsplit方法,如果不指定分割府,则字符串中的任何空白符号(包括空格,换行符,制表夫)的连续出现都将被分为分割府
s_b = 'hello world \n \n My name is xiexukang \t\t'
print(s_b.split())#result:['hello', 'world', 'My', 'name', 'is', 'xiexukang']



#lower(),upper(),capitalize(),title(),swapcase()
#lower,upper()将字符串转换为小写,大写,
s_temp = "XIEX U KANG"
print(s_temp.title())#result:Xiexukang title()返回的是每个单词首字母大写
print(s_temp.lower())#result:xiexukang
s_temp = "XIEX U KANG"
print(s_temp.capitalize())#resilt:
#swapcase()大小写互换
s_temp = "What is yOu Name"
print(s_temp.swapcase())#result:wHAT IS YoU nAME
#maketrans(),translate()
#maketrans()用来生成字符映射表,而translate()方法则按映射表中定义的对应关系转换字符串并替换其中的字符
table =''.maketrans('abcdef123','uvwxyz@#$')#映射关系
s = "Python is a greate programming language. I like it!"
print(s.translate(table))#result:Python is u gryuty progrumming lunguugy. I liky it!
#use the maketrans and translate() to generate some password
import string
begin = string.ascii_lowercase + string.ascii_uppercase
end = begin[3:10]+begin[:3]+begin[20:]+begin[10:20]
table = ''.maketrans(begin,end)
your_input = "input('input the word to translate:')"
print(your_input.translate(table))

#strip(),rstrip(),lstrip()可以用来删除两端,右端,左端空白字符或指定字符。
s = "abc ww"
print(s.strip())#result:abc ww因为两端不存在空的字符串


#inner function eval() can translate any string to Python expression and cal
print(eval('3+4'))#result:7
a = 3
b =4
c = -2
print(eval('a+b*c'))#result: -5
#in can judge a string have some word
words = ('测试','非法','暴力','花')
text = '这句话要的就是非法和暴力,测试大家的反映速度'
for temp_word in words:
	if temp_word in text:
		text=text.replace(temp_word, '***')#result:这句话要的就是***和***,***大家的反映速度

print(text)
#startswith(),endswith()测试字符串是否以某开头或者结尾可以接收一个字符串元组作为参数来表示前缀或着后缀
if text.startswith(('这句话','非法','暴力')): #result:yes
	print("yes")
#isalnum()测试字符串是否为数字或字母
test_str = "x12"
print(test_str.isalnum())#result:true
#isalpha 是否为字母,isdigit 是否为数字, isspace 是否为空白字符,isupper 是否为大写字符
#islower 是否为小写字符 注意:isnumeric()方法支持汉字数字
#unicodedate提供了不同形式的数字字符到十进制数字的转换方法
import unicodedata
print(unicodedata.numeric('2'))#result:2.0
print(unicodedata.numeric('九'))#result:9.0
#center():居中对齐,ljust():左对齐,rjust():right same location,zfill():返回指定宽度的字符串,在左侧以字符0填充
print('xxk'.center(20, '~'))#reuslt:~~~~~~~~xxk~~~~~~~~~
print('xxk'.ljust(10, '*'))#result:xxk*******
print('xxk'.rjust(10, ')'))#result:)))))))xxk
print('xxk'.zfill(4))#result:0xxk
text_to_format = '''The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!'''
#python 标准库textwrap提供了更加友好的排版函数
import textwrap
print(textwrap.fill(text_to_format,width=80))#按指定矿度进行排序,默认长度最大为70
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值