pytho系统学习:第二周之字符串函数练习

# Author : Sunny
# 双下划线的函数基本没用
# 定义字符串
name = 'i am sunny!'
# 首字母大写函数:capitalize
print('-->capitalize:', name.capitalize())
# 判断结尾函数:endswith
print('-->endswith:', name.endswith('y!'))
# 判断开头函数:startswith
print('-->startswith:', name.startswith('i'))
# 字符输出居中函数:center
print('-->center:', name.center(30, '+'))
# 字符计数函数:count
print('-->count:', name.count('n'))
# tab键输出转空格函数:expandtabs //不重要
name2 = 'su\tnny!'
print('-->expandtabs:', name2.expandtabs(30))
# 字符位置判断函数:find
print('-->find:', name.find('n')) # 返回左面第一个n的索引值
print('-->rfind:', name.rfind('n')) # 返回右面第一个n的索引值
print('-->find切片应用:', name[name.find('s'):]) # 字符find的切片应用
# 字符格式转化(参数传值)函数:format
name = 'sunny'
age = 23
print('-->format用法一:', '{0} is {1} years old!'.format(name, age)) # format用法一
word = '{name} is {age} years old!'
print('-->format用法二:', word.format(name='sunny', age=23)) # format用法二
print('-->format用法三:', word.format_map({'name': 'sunny', 'age': 23})) # format_map字典用法 //不常用
# 判断字符是否是数字组成函数:isalnum
print('-->isalnum:', '123'.isalnum())
# 判断字符是否纯字母组成函数:isalpha
print('-->isalpha:', 's5'.isalpha())
# 判断字符是否十进制函数:isdecimal
print('-->isdecimal:', '1'.isdecimal())
# 判断字符是否是整数:isdigit
print('-->isdigit:', '55'.isdigit())
# 判断字符是否是纯数字:isnumeric
print('-->isnumeric:', 's45'.isnumeric())
# 判断字符是否是合法标识符:isidentifier //不常用
print('-->isidentifier:', 'as'.isidentifier())
# 判断字符是否都是小写函数:islower
print('-->islower:', 'aAa'.islower())
# 字符串转化为小写函数:lower
print('-->lower:', 'ADW'.lower())
# 判断字符是否为空格函数:isspace
print('-->isspace:', ' '.isspace())
# 判断字符首字母是否为大写函数:istitle
print('-->istitle:', 'I Am'.istitle()) # 都为大写则为true
# 将字符首字母都转化为大写函数:title
print('-->title:', name.title())
# 判断字符串是否为大写函数:isupper
print('-->isupper:', name.isupper())
# 将字符串转化为大写函数:upper
print('-->upper:', name.upper())
# 列表值关联函数:join
print('-->join:', '+'.join(['1', '2', '3'])) # 列表值为字符串
# 字符串长度补齐函数:ljust/rjust
print('-->ljust:', name.ljust(30, '+'))
# 去除字符串空格函数:strip/lstrip/rstrip
print('-->lstrip:', ' asad'.lstrip())
# 字符自定义加密函数:maketrans
dirc = str.maketrans('w13hc1g4', '\/?@#%^&')
print('-->maketrans:', 'wghc1314'.translate(dirc))
# 字符串替换函数:replace
print('-->replace:', name.replace('n', 'u'))
# 字符串分割成列表函数:split
print('-->split:', '1+2+3+4'.split('+'))
# 字符串大小写互换函数:swapcase
print('-->swapcase:', name.swapcase())

字符串的函数基本就这些,如果有什么疑问,可以关注我的博客,我们一起讨论

猜你喜欢

转载自www.cnblogs.com/niushichong/p/9901231.html