python3 字符串相关函数

python版本 3.5

#Author by Liguangbo
#_*_ coding:utf-8 _*_
str="i like study python, welcome to my python program\t."
#首字母大写
print(str.capitalize())
#I like study python, welcome to my python program.
#关键字在字符串中出现的次数
print(str.count(" "))
#8
#打印100个字符,如果str不够,则用-代替,且字符str位于中间
print('hello world'.center(20,'-'))
#----hello world-----
#判断字符串是否以‘l’和‘.’开头结尾
print(str.startswith('l'))
#False
print(str.endswith('.'))
#True
#将tab键转为5个空格
print(str.expandtabs(tabsize=51))
#i like study python, welcome to my python program .
#查找第一个sub出现的位置
sub='p'
print(str[str.find(sub):])
#python, welcome to my python program .
#字符串的参数调用及赋值
s="my name is {name},i am {years} years old!"
print(s.format(name="ligb",years="28"))
print(s.format_map({'name': 'ligb' ,'years':28}))
#my name is ligb,i am 28 years old!
#判断是否是由阿拉伯数字或字母组成,不能包含符号、空格
x='我'
print(x.isalnum())
#True
#判断是否是纯字符,不能包含数字或者符号
print(x.isalpha())
#True
print('一'.isdecimal())
#False
print('1'.isdigit())
#True
#判断是否是小写、大写
print('a'.islower())
#True
print('a'.isupper())
#False
#判断是否所有单词首字母大写
print('My Name Is '.istitle())
#True
#判断文件是否可以打印
print('my name is ligb'.isprintable())#tty drive等文件不可打印
#True
#列表转字符串
print('%'.join(['wo','men','de','jia']))
#wo%men%de%jia
#若字符串长度不够20,则在末尾加*补充
print('hello world'.ljust(20,'*'))
#hello world*********
print('hello world'.rjust(20,'*'))
#*********hello world
#大小写转换
print('hello world'.lower())
print('hello world'.upper())
#hello world
#HELLO WORLD
#去掉首尾的回车或者换行
print(' hello world\n'.strip())
print('-----')
#hello world
#-----
#去掉左右的回车或者换行
print(' hello world\n'.rstrip())
print(' hello world\n'.lstrip())

#查找最右边的关键字
print('hello world !'.rfind('world'))
#以空格为分割符,生成列表
print(' '.join('hello world my name is'.split()))
print('hello world my name is'.split())
#['hello', 'world', 'my', 'name', 'is']
print('hello+world+my+name+is'.split('+'))
#['hello', 'world', 'my', 'name', 'is']
#按照换行来分
print('hello \n world'.splitlines())
#['hello ', ' world']
#调换大小写
print('Hello World'.swapcase())
#hELLO wORLD
print('hello world'.title())
#Hello World
posted @ 2016-11-27 08:04  想自由  阅读(1663)  评论(0编辑  收藏  举报