python字符串方法

1、center

方法center通过在两边添加填充字符(默认为空格)让字符串居中。
      >>> "The Middle by Jimmy Eat World".center(39)
      ' The Middle by Jimmy Eat World '
      >>> "The Middle by Jimmy Eat World".center(39, "*")
      '*****The Middle by Jimmy Eat World*****'

2、find

方法find在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1。
      >>> 'With a moo-moo here, and a moo-moo there'.find('moo')
      7
      >>> title = "Monty Python's Flying Circus"
      >>> title.find('Monty')
      0
      >>> title.find('Python')

      6
      >>> title.find('Flying')
      15
      >>> title.find('Zirquss')
      -1

 

3、join

join是一个非常重要的字符串方法,其作用与split相反,用于合并序列的元素。
       >>> seq = [1, 2, 3, 4, 5]
      >>> sep = '+'
      >>> sep.join(seq) # 尝试合并一个数字列表
      Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      TypeError: sequence item 0: expected string, int found
      >>> seq = ['1', '2', '3', '4', '5']
      >>> sep.join(seq) # 合并一个字符串列表
      '1+2+3+4+5'
      >>> dirs = '', 'usr', 'bin', 'env'
      >>> '/'.join(dirs)
     '/usr/bin/env'
     >>> print('C:' + '\\'.join(dirs))
     C:\usr\bin\env

4、lower

方法lower返回字符串的小写版本。
      >>> 'Trondheim Hammer Dance'.lower()
      'trondheim hammer dance'

 

5、replace

方法replace将指定子串都替换为另一个字符串,并返回替换后的结果。
      >>> 'This is a test'.replace('is', 'eez')
      'Theez eez a test'

 

6、split

split是一个非常重要的字符串方法,其作用与join相反,用于将字符串拆分为序列。
      >>> '1+2+3+4+5'.split('+')
      ['1', '2', '3', '4', '5']
      >>> '/usr/bin/env'.split('/')
      ['', 'usr', 'bin', 'env']
      >>> 'Using the default'.split()
      ['Using', 'the', 'default']

 

7、strip

方法strip将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。
      >>> ' internal whitespace is kept '.strip()
      'internal whitespace is kept'

 

8、isspace、isdigit和isupper等等以is开头的方法

它们判断字符串是否具有特定的性质(如包含的字符全为空白、数字或大写)。

如果字符串具备特定的性质,这些方法就返回
True,否则返回False。

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值