初识python: 常用字符串操作

Posted Simple-Sir

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了初识python: 常用字符串操作相关的知识,希望对你有一定的参考价值。

 

直接上代码示例:

 

#!/user/bin env python
# author:Simple-Sir
# time:20180914
# 字符串常用操作
name = \'lzh lyh\'
print(\'capitalize返回值:\',name.capitalize()) # 首字母大写
print(\'count返回值:\',name.count(\'l\')) #指定字母数量
print(\'center返回值:\',name.center(50,\'-\')) #共打印50个字符,不够的用“-”补充,且将nmae字符串放在中间
print(\'encode返回值:\',name.encode()) #字符转字节
print(\'endswith返回值:\',name.endswith(\'yh\')) #判断字符串是否以指定值结尾

str1 = \'这是一个\\tTAB建转换\'
print(\'expandtabs返回值:\',str1.expandtabs(tabsize=30)) #将tab建转成30个空格。

print(\'find返回值:\',name.find(\'l\')) #获取指定字符串中第一个字符的位置
print(\'rfind返回值:\',name.rfind(\'l\')) #返回指定字符从右往左出现的第一个字符位置

str2 = \'my name is {name},i am {year} old.\'
print(\'format返回值:\',str2.format(name=\'simple\',year=25)) #格式化输出
print(\'format_map返回值:\',str2.format_map( {\'name\':\'simple\',\'year\':25} ))

str3 = \'simple123好\'
print(\'isalnum返回值:\',str3.isalnum()) #判断字符是否由阿拉伯数字和字母组成(即:若包含特殊字符则:False)
print(\'isalpha返回值:\',str3.isalpha()) #是否纯英文字符组成

str4 = \'122\' #定义一个十进制字符串,只需要在字符串前添加 \'u\' 前缀即可。
print(\'isdecimal返回值:\',str4.isdecimal()) #如果字符串只包含十进制字字符返回True,否则返回False。

str5 =\'23\'
print(\'isdigit返回值:\',str5.isdigit()) #是否为整数
print(\'isidentifier返回值:\',\'name\'.isidentifier()) #判断是否是一个合法的变量名
print(\'islower返回值:\',\'lzh123\'.islower()) #判断字母是否全是小写字母
print(\'isupper返回值:\',\'LZH123\'.isupper()) #判断字母是否全是小写字母
print(\'isnumeric返回值:\',\'123\'.isnumeric()) #判断是否是全是数字组成
print(\'isspace返回值:\',\'    \'.isspace()) #判断是否全是空格
print(\'istitle返回值:\',\'My name is\'.istitle()) #判断每个单词首字母是否大写

print(\'join返回值:\',\'合并\'.join([\'1\',\'2\',\'3\'])) #将指定值放入到...
print(\'ljust返回值:\',name.ljust(50,\'*\')) #共打印50个字符,不够的在右侧用“*”补充
print(\'rjust返回值:\',name.rjust(50,\'*\')) #共打印50个字符,不够的在左侧用“*”补充

print(\'lower返回值:\',\'Simple\'.lower()) #将大写变小写
print(\'upper返回值:\',\'simple\'.upper()) #将小写变大写

print(\'strip返回值:\',\' simple \'.strip()) #取消两边空格和回车
print(\'lstrip返回值:\',\' simple \'.lstrip()) #取消左边空格和回车
print(\'rstrip返回值:\',\' simple \'.rstrip()) #取消右边空格和回车

p = str.maketrans(\'absi\',\'1234\')
print(\'maketrans返回值:\',\'simple\'.translate(p)) #对应转换,可延生加密方式

print(\'replace返回值:\',\'simple sir\'.replace(\'s\',\'L\',2)) #将指定值替换成另一个值,并选择替换几个

print(\'split返回值:\',\'1+2+3+4\'.split(\'+\')) #将字符串以指定字符为分隔符分割成一个列表
print(\'splitlines返回值:\',\'1+2+3\\n+4\'.splitlines()) #同上,以换行符作为分割符

print(\'swapcase返回值:\',\'Simple Sir\'.swapcase()) #大小写互换

print(\'title返回值:\',\'simple sir\'.title()) #将每个单词首字母大写
字符串常用操作

 

 

 

 执行结果:

 

以上是关于初识python: 常用字符串操作的主要内容,如果未能解决你的问题,请参考以下文章

python初识-day3

常用python日期日志获取内容循环的代码片段

python常用代码片段总结

博客目录

Python 第2周 - Python基础-模块数据运算

python常用模块初识