python字符串常用函数

92 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情


大家好,我是芒果,一名非科班的在校大学生。对C/C++、数据结构、Linux及MySql、算法等领域感兴趣,喜欢将所学知识写成博客记录下来。 希望该文章对你有所帮助!如果有错误请大佬们指正!共同学习交流

作者简介:



strip函数

去除字符串开头结尾的空格/制表符 strip函数

空白字符:空格,换行,tab

a = '       hello world             '
print(a.strip())    #hello world

去掉左侧的空白字符:lstrip

去掉右侧的空白字符: rstrip

a ='    hello   \n'
print(f'[{a.lstrip()}]')    #为了方便看,加上[]
print(f'[{a.rstrip()}]')
print(f'[{a.strip()}]')
#执行结果:
[hello   
]
[    hello]
[hello]

ljust rjust center函数

左对齐/右对齐/中间对齐 ljust rjust center函数

a = '    hello world'
print(a.ljust(30))
print(a.rjust(30))
print(a.center(30))
#执行结果:
    hello world               
                   hello world
           hello world        
find函数

查找子串 find函数

a = '    hello world'
print(a.find('hello'))  #4
a = 'hello hello '
print(a.find('h'))  #0

返回第一次出现的下标

in差不多,in返回的是布尔值

a = '    hello world'
print(a.find('hello'))  #4
print('hello' in a) #True

replace函数

替换子串(记得字符串是不可变对象, 只能生成新字符串). replace函数

a=  'hello world'
print(a.replace('world','python'))  #hello python
print(a)    #hello world    字符串是不可变对象, 只能生成新字符串

isalpha函数 和 isdigit函数

判定字符串是字母/数字 isalpha函数 和 isdigit函数

a = 'hello 1'
print(a.isalpha())  #False
a = '1234'
print(a.isdigit())  #True

lower和upper函数

转换大小写 lower和upper函数

a = 'Hello world'
print(a.lower())    #hello world
print(a.upper())    #HELLO WORLD

关于结束符

学过C语言的同学, 可能会问, Python的字符串是否需要 '\0' 之类的结束符来做结尾?

  • Python中并没有那个讨厌的 '\0' . 准确的说, 对于C语言来说, 语言本身的缺陷并不支持 "字符串类型", 才被迫使用字符数组来凑合. 但是Python完全没有这个包袱.