python函数

注意:函数以用途分类

所用到的函数:

# 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',

# 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit',

# 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join',

# 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace',

# 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',

# 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill





print('大小写转换')

temp='i lovE pyTHon'

print(temp)

# capitalize

print('# capitalize')

print(temp.capitalize())

# 将字符串的第一个字母变成大写,其余字母变为小写



# casefold

print('# casefold ')

print(temp.casefold())

# 都变成小写



# title

print('# title')

print(temp.title())

# 返回一个满足标题格式的字符串。将英文单词首字母大写,其余英文字母小写.



print('# swapcase()')

print(temp.swapcase())

# 大写变小写,小写变大写




print(temp.lower())

# 字符串中的大写变小写



print(temp.upper())

# 小写字母转换为大写字母



# casefold()

one='i LovE pythoN &*&*&*&* $@ #@ $'

print(one)

print('# casefold')

print(one.casefold())

# 大写字母转换为小写字母    也可将非英文 语言中的大写转换为小写



# 分割字符串

print('# partition')

string="http://localhost:8888/lab/tre.ipynb"

print(string.partition('http:'))

#v字符串str中存在sep

print(string.partition(':ll'))

#字符串str中不存在sep






# 根据指定的分隔符(sep)将字符串进行分割。从字符串左边开始索引分隔符sep,索引到则停止索引




print('# rpartition')

print(string.rpartition('://lo'))

print(string.rpartition(':/lo'))

# 根据指定的分隔符(sep)将字符串进行分割。从字符串右边开始索引分隔符sep,索引到则停止索引





print('# split')

string2='ak;djpa;wougxG;kajdll;dskhakkd;ajdakda;djaih slajs;sjja sjla;aiw'

print('string=',string2)

print(string2.split(';'))

print(string2.split(';',3))

print(string2.split(';',3)[3])



# >>> help('os'.split)

# Help on built-in function split:

# split(sep=None, maxsplit=-1) method of builtins.str instance

#     Return a list of the words in the string, using sep as the delimiter string.

#     sep

#       The delimiter according which to split the string.

#       None (the default value) means split according to any whitespace,

#       and discard empty strings from the result.

#     maxsplit

#       Maximum number of splits to do.

#       -1 (the default value) means no limit.




# 拆分字符串。通过指定分隔符sep对字符串进行分割,并返回分割后的字符串列表。从字符串右边(末尾)开始分割。



print('# rsplit')



print(string2.rsplit(';'))

print(string2.rsplit(';',2))

print(string2.rsplit(';',3)[2])



# 区别split  从字符串左边(末尾)开始分割。





print('# splitlines')

string3='ak;da\n;wgxG;kajdll; d\ns\nk\nh\na\n    @@kkd;akda;d/rj\ra\rih  @@sla\tj\ts\t;\n\r  !!sj\n\rja sjla;aiw'



print(string3.splitlines())

# 去掉换行符



print(string3.splitlines(True))

# 保留换行符

# >>> help('os',splitlines)

# Traceback (most recent call last):

#   File "<stdin>", line 1, in <module>

# NameError: name 'splitlines' is not defined




print('# join')

string4='jhjahdkahk'

print('&   &'.join(string4))

l1={'abc','jj','P'}

print('*'.join(l1))


 


# 解决判断问题

# endswith

temp='i love python'

print(temp)

print('# endswith')

print(temp.endswith('n'))

print(temp.endswith('i'))

print(temp.endswith('on'))

print(temp.endswith('love python'))

print(temp.endswith('love',1,7))

print(temp.endswith('love',0,6))

print(temp.endswith(''))



# 判断字符串是否以指定字符或子字符串结尾,返回类型为布尔类型(bool).并且可以指定start 和 end.

# startswith (区别 endswith)

print('# startswith')

# "hello,i love python".startswith(("h")

print(temp.startswith('i'))

print(temp.startswith('n'))

print(temp.startswith('lo',2,len(temp)))

print(temp.startswith('a'))



# isalnum   (alnum 字母 数字)

print('# isalnum')

print(temp.isalnum())

one='shkhskh'

two='6378720079'

three='464jhdaiud'

four=' '

print(one.isalnum())

print(two.isalnum())

print(three.isalnum())

print(four.isalnum())

# 判断非空字符串是否为都为字母或数字,返回值为bool类型

                                 

# isalpha      (alphabet 字母表)

print('# isalpha')

print(temp.isalpha())

print(one.isalpha())

print(two.isalpha())

print(three.isalpha())

# 判断非空字符串是否为都是字母,返回值为bool类型



# isdecimal  (decimal 十进制)

print('# isdecimal')

print(temp.isdecimal())

print(one.isdecimal())

print(two.isdecimal())

print(three.isdecimal())

# 判断非空字符串是否为都是(十进制的)数字,返回值为bool类型



print('# isdigit')

print(temp.isdigit())

print(one.isdigit())

print(two.isdigit())

print(three.isdigit())

# 判断非空字符串是否为都是(0->9的)数字,返回值为bool类型



print('# isidentifier')

five='_hakha'

print(temp.isidentifier())

print(one.isidentifier())

print(two.isidentifier())

print(three.isidentifier())

print(five.isidentifier())

print()

# 判断非空字符串是否为都是(有效)identifier(标识符),返回值为bool类型



print('# islower')

six='你好,python'

print(temp.islower())

print(one.islower())

print(two.islower())

print(five.islower())

print(six.islower())



# 判断非空字符串是否存在小写字母,返回值为bool类型



# isnumeric

print('# isnumeric')

print(temp.isnumeric())

print(one.isnumeric())

print(two.isnumeric())

print(five.isnumeric())

print(six.isnumeric())

# 判断非空字符串是否任意字符是numerical(数字),返回值为bool类型



print('# isprintable')

print(temp.isprintable())

print(six.isprintable())

print('hakh \n shf \t hk'.isprintable())

# 判断非空字符串是否存在printable(打印后不可见的内容。如:\n \t  等字符),返回值为bool类型



print('# isspace')

print(temp.isspace())

print(temp[1].isspace())

print(four.isspace())

eight=' sjs sjla ajs'

print(eight.isspace())

# 判断非空字符串是否仅有space(空格),返回值为bool类型




print('# istitle')

print(temp.istitle())

print('I love python'.istitle())

print('Ijsj'.istitle())

print('IhkdLGVkh'.istitle())

print('Gjakssk'.istitle())

# 判断字符串中所有单词的首字母是否为大写,且其它字母是否为小写,字符串中可以存在其它非字母的字符

# 统计字符次数

print('# count')

# 统计字符串里某个字符出现的次数。可以选择字符串索引的起始位置和结束位置。

# >>> help('os'.count)

# Help on built-in function count:

# count(...) method of builtins.str instance

#     S.count(sub[, start[, end]]) -> int

#     Return the number of non-overlapping occurrences of substring sub in

#     string S[start:end].  Optional arguments start and end are

#     interpreted as in slice notation.



temp='hakhdjljozjzOslljlpoapzzjoaio4khan'

print(temp.count('z',1,len(temp)))

print(temp.count('z',10,len(temp)))

print(temp.count('l',2,12))


# 字符串编码

one='i love python'

two='python'

print('one= ')

print(one)

print('two= ')

print(two)

print()

# encode  指定的编码格式编码字符串

print(two.encode())

"I love my country".encode(encoding="utf8",errors="strict")

"时间简史".encode(encoding="utf8",errors="strict")

# >>> help('os'.encode)

# Help on built-in function encode:



# encode(encoding='utf-8', errors='strict') method of builtins.str instance

#     Encode the string using the codec registered for encoding.



#     encoding

#       The encoding in which to encode the string.

#     errors

#       The error handling scheme to use for encoding errors.

#       The default is 'strict' meaning that encoding errors raise a

#       UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and

#       'xmlcharrefreplace' as well as any other name registered with

#       codecs.register_error that can handle UnicodeEncodeErrors.



# decode()  指定的编码格式解码字符串,默认编码为字符串编码。decode英文意思是 解码,



print('# decode')

# >>> help('os'.decode)

# Traceback (most recent call last):

#   File "<stdin>", line 1, in <module>

# AttributeError: 'str' object has no attribute 'decode'




str1 = "你好".encode(encoding="utf8")

str2=str1.decode(encoding="utf8")

print(str2)

print('')

("时间简史".encode(encoding="utf8",errors="strict")).decode(encoding="utf_8")

print(("时间简史".encode(encoding="utf8",errors="strict")).decode(encoding="utf_8"))  

#解码"时间简史".encode(encoding="utf8",errors="strict") 为 decode(encoding="utf_8")




 

# 字符串查找



temp='i love python'

one='aihkha HJFH ajiajs'

print(temp)

print(one)

# find    自左向右的第一个位置

print('# find')

print(one.find('a'))

print(one.find('a',5))

print(one.find('a',6))

print(one.find('a',13,20))

len(one)

print(one.find('a',6,len(one)))

# >>> help('os'.find)

# Help on built-in function find:

# find(...) method of builtins.str instance

#     S.find(sub[, start[, end]]) -> int

#     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.



# rfind   自右向左的第一个位置

print('# rfing:')

print(one.rfind('a',6,len(one)))



print('# index')

print(one.index('a'))

# print(temp.index('a'))   会报错

temp.index('o')

temp.index('o',4,len(temp))



print('# rindex')

temp.rindex('o',4,len(temp))

# 查找方向与index相反   (r=right l=left)



 

# 字符串格式化

#format



i=1462783.19133459

print('# 数据格式化')

print("i=",i)

print(format(i,'.2f'))



# 科学计数法

print(format(i,'e'))

print(format(13546.14648,'.2e'))

# 指定最小宽度

print(format(i,'20,.2f'))

# 百分数 %

print(format(i,'%'))

print(format(i,'.3%'))

# 整数

print(format(85,'10d'))

print(format(i,'15,.2f'))



# print(format(i, sep=''))

# print(format('464 ','898412218''sep''))



# {}的应用

print('{} lo{} py{}'.format('i','ve','thon'))





# >>> help('os'.format)

# Help on built-in function format:

# format(...) method of builtins.str instance

#     S.format(*args, **kwargs) -> str

#     Return a formatted version of S, using substitutions from args and kwargs.

#     The substitutions are identified by braces ('{' and '}').




# 提升

temp={'one','two','three'}

for i in temp:

    print('{}:love python'.format(i))

    print('{}:love python'.format(i.center(10,'*')))




print()

# for循环进行批量处理



print(['i love python_{}'.format(i) for i in list('sjalj')])

 # format_map  # 返回字符串的格式化版本




 

# 字符串加密解密

# >>> help('os'.maketrans)

# Help on built-in function maketrans:

# maketrans(...)

#     Return a translation table usable for str.translate()

#     If there is only one argument, it must be a dictionary mapping Unicode

#     ordinals (integers) or characters to Unicode ordinals, strings or None.

#     Character keys will be then converted to ordinals.

#     If there are two arguments, they must be strings of equal length, and

#     in the resulting dictionary, each character in x will be mapped to the

#     character at the same position in y. If there is a third argument, it

#     must be a string, whose characters will be mapped to None in the result.



a = 'sjhakh sahkh skahppp'

c='abcdfg'

b = c.maketrans('ABCDFG',c) # {65: 97, 66: 98, 67: 99, 68: 100, 70: 102, 71: 103}

z = str.maketrans(b)

print(a.translate(z))

print(c.translate(z))



print()

# 有两个参数,则两个参数形成对应关系且两个参数的长度一致

b = a.maketrans('shak','****')

d = c.maketrans('ABCDFG',c)     # 必须满足len('ABCDDFG')=len(c)  

print(a.translate(b))

print()

print(b)

# print(b.translate())

print(d)

# 如果有第三个参数则第三个参数必须是字符串,该字符串将自动映射到none(就是返回的值直接删除第三个参数的内容)

g = a.maketrans('GGGGG','##&&#','sj')    

# 第三个字符串 自动定映射到none 直接省略

print(a.translate(g))

print(g)



print('ef:来自AI')

table = str.maketrans('abcdf p', '923458A')  # 同上(必须满足len('ABCDDFG')=len(c))  

# 创建映射表

string = 'habccasjahsdkhakba zkzhkhppzzbvsambaxba'

new_string = string.translate(table)

print(new_string)

# 替换字符串中的字符



# maketrans是一个静态函数,用于生成一个映射表,供translate使用(对照),如果maketrans 仅一个参数,则该参数必须是一个字典;

# 如果是接受两个参数,两个等长的字符串,用于指定要替换的字符和替换的目标字符

# 要么是一个长度为 1 的字符串,字典的 value 则可以是任意字符串、None或者 Unicode 编码。

# translate()函数用于对字符串进行字符替换操作,它接受一个映射表作为参数,将字符串中的指定字两个参数符替换为目标字符。这个函数返回替换后的新字符串。


# 字符串替换

print('# replace')

temp='i love python'

one='hello'

print(temp,one)

print(temp.replace(temp,one))

print(temp.replace('love',one))

print(one.replace('e',temp))





# >>> help('os'.replace)

# Help on built-in function replace:

# replace(old, new, count=-1, /) method of builtins.str instance

#     Return a copy with all occurrences of substring old replaced by new.

#       count

#         Maximum number of occurrences to replace.

#         -1 (the default value) means replace all occurrences.

#     If the optional argument count is given, only the first count occurrences are

#     replaced.



print('# expandtabs')

# 将字符串S中的 \t 替换为一定数量的空格

print('hakhsakahd    jdh\thaA'.expandtabs(16))

print('hakhsakahd    jdh\thaA\tGGG    LL'.expandtabs(12))


 

# center()

one='i love python'

two='python'

print('one= ')

print(one)

print('two= ')

print(two)

print('# center')

print(one.center(5))

print(two.center(10))

print(two.center(10,'&'))



# >>> help('os'.center)

# Help on built-in function center:

# center(width, fillchar=' ', /) method of builtins.str instance

#     Return a centered string of length width.

#     Padding is done using the specified fill character (default is a space).



# ljust()

print('# ljust()')

print(two.ljust(15))     # fillchar 默认为空格

print(two.ljust(15,'@'))

print('')

# 第一个空为宽度(width)  第二个空为fillchar

# 字符串优先向左对齐,并占用width 和在空width填入fillchar

print('提升')

L = ['two','peter',two]

for name in L:

    print(name)

for name in L:

    print(name.ljust(10,'#'))



#rlist

print('# rjust')

print(one.rjust(20))

print(one.rjust(20,'*'))

# 由ljust同理可知rjust

# zfill

print('# zfil')

print(two.zfill(20))

# 区别rjust, fillchar为 0


# 字符串修剪

temp='i love python'

print('temp = ',temp)

print('# strip')

print(temp.strip('i'))

print(temp.strip('python'))

print(temp.strip('lo'))

print(temp.strip('i lo'))

print('IIIIIhdsdjgjdaiIIIII'.strip('IIIII'))

print('494454dkka6494'.strip('494'))

# strip作用是去除字符串开头和结尾处指定的字符,不会去除字符串中间对应的字符



print('# lstrip')

print('jksghhhhHUUUUUUjksg'.strip('jksg'))

print('jksghhhhHUUUUUUjksg'.lstrip('jksg'))

print('gsaGGGGGGGags'.lstrip('GGGGGGG'))

print('gsaHHJJgsa'.lstrip('gsa'))

# trip()用于截掉字符串左边的空格或指定字符



print('# rstrip')

print('hsakhUUUUhsa'.rstrip('hsa'))

# 删除字符串末尾(右边)的指定字符(默认为空格)

# 有很多不足之处,请谅解。欢迎其他大神留言,我好进步。谢谢。

#看到这里点个赞吧,谢谢大佬。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值