Python字符串的常用方法+实例—— 调整排版
在python中,它是一种不可变序列;
#判断空白字符
space_str = " \t\r\n"
print(space_str.isspace()) #返回True
判断数字
isdecimal( ) 方法 能判断:阿拉伯数字;小数、Unicode字符、汉字数字和罗马数字则不能判断。
**isdigit( )**方法 能判断:阿拉伯数字和Unicode字符;小数、、汉字数字和罗马数字则不能判断。
**isnumeric()**方法 能判断:阿拉伯数字和Unicode字符、汉字数字和罗马数字;小数则不能判断。
替换字符串
# replace方法执行完成之后,会返回一个新的字符串,不会修改原有字符串的内容
hello_str = "hello hello word"
print(hello_str.replace("he", "11"))
print(hello_str)
print(hello_str.replace("he", "He", 2)) # 指定替换的次数
大小写转换
s = "what IS yOUr NAMe?"
print(s.capitalize()) #第一个字符大写
print(s.title()) #每个单词首字符大写
print(s.lower()) #大写换小写
print(s.upper()) #小写换大写
print(s.swapcase()) #翻转大小写
去除空白字符
s = " abc \t"
print(s.strip()) #去两边空白符
print(s.lstrip()) #去除左边空白符
print(s.rstrip()) #去除右边空白符
这三个函数如果指定参数时,可以删除指定的字符。参数指定的字符串并不作为一个整体对待,而是在原字符串的两侧、右侧、左侧删除参数字符串中包含的所有字符,一层一层地从外往里扒。
s1 = "aabbccdaabbccd"
print(s1.strip("ad")) #去除;两边
print(s1.lstrip("abd")) #去除从左边符
print(s1.rstrip("acd")) #去除从右边符
文本对齐
s2 = "abc"
print(s2.center(20, "*")) #居中对齐
print(s2.ljust(10, "#")) #居左对齐
print(s2.rjust(10, "-")) #居右对齐
实例—— 调整排版
poem = ["\t\n夜雨寄北 ",
"李 商 隐",
"君问 归期未 有 期\t\n",
"巴 山夜 里涨秋 池 ",
" 何 当 共剪西 窗 烛",
" 却 话巴山 夜 雨时 "]
for line in poem:
print(line.replace(" ", "").strip().center(10, " "))
还没有评论,来说两句吧...