Python字符串的常用方法+实例—— 调整排版

痛定思痛。 2023-07-24 02:14 64阅读 0赞

在python中,它是一种不可变序列;

  1. #判断空白字符
  2. space_str = " \t\r\n"
  3. print(space_str.isspace()) #返回True

在这里插入图片描述

判断数字
isdecimal( ) 方法 能判断:阿拉伯数字;小数、Unicode字符、汉字数字和罗马数字则不能判断。

**isdigit( )**方法 能判断:阿拉伯数字和Unicode字符;小数、、汉字数字和罗马数字则不能判断。

**isnumeric()**方法 能判断:阿拉伯数字和Unicode字符、汉字数字和罗马数字;小数则不能判断。
在这里插入图片描述
替换字符串

  1. # replace方法执行完成之后,会返回一个新的字符串,不会修改原有字符串的内容
  2. hello_str = "hello hello word"
  3. print(hello_str.replace("he", "11"))
  4. print(hello_str)
  5. print(hello_str.replace("he", "He", 2)) # 指定替换的次数

大小写转换
在这里插入图片描述

  1. s = "what IS yOUr NAMe?"
  2. print(s.capitalize()) #第一个字符大写
  3. print(s.title()) #每个单词首字符大写
  4. print(s.lower()) #大写换小写
  5. print(s.upper()) #小写换大写
  6. print(s.swapcase()) #翻转大小写

去除空白字符

在这里插入图片描述

  1. s = " abc \t"
  2. print(s.strip()) #去两边空白符
  3. print(s.lstrip()) #去除左边空白符
  4. print(s.rstrip()) #去除右边空白符

这三个函数如果指定参数时,可以删除指定的字符。参数指定的字符串并不作为一个整体对待,而是在原字符串的两侧、右侧、左侧删除参数字符串中包含的所有字符,一层一层地从外往里扒。

  1. s1 = "aabbccdaabbccd"
  2. print(s1.strip("ad")) #去除;两边
  3. print(s1.lstrip("abd")) #去除从左边符
  4. print(s1.rstrip("acd")) #去除从右边符

在这里插入图片描述
文本对齐

  1. s2 = "abc"
  2. print(s2.center(20, "*")) #居中对齐
  3. print(s2.ljust(10, "#")) #居左对齐
  4. print(s2.rjust(10, "-")) #居右对齐

实例—— 调整排版

  1. poem = ["\t\n夜雨寄北 ",
  2. "李 商 隐",
  3. "君问 归期未 有 期\t\n",
  4. "巴 山夜 里涨秋 池 ",
  5. " 何 当 共剪西 窗 烛",
  6. " 却 话巴山 夜 雨时 "]
  7. for line in poem:
  8. print(line.replace(" ", "").strip().center(10, " "))

发表评论

表情:
评论列表 (有 0 条评论,64人围观)

还没有评论,来说两句吧...

相关阅读