Python中的字符串(搜索和替换、对齐、统计、分离和连接)

1、字符串的搜索和替换

  s = 'hello world hello'

  #find找到子串,并返回最小的索引
  print(s.find('hello'))
  print(s.find('world'))

  #rfind找到子串,并返回最大的索引
  print(s.rfind('hello'))

  #替换
  print(s.replace('hello','westos'))

在这里插入图片描述

2、字符串对齐

  print('学生管理系统'.center(30))
  print('学生管理系统'.center(30,'*'))
  print('学生管理系统'.ljust(30,'*'))
  print('学生管理系统'.rjust(30,'*'))

在这里插入图片描述

3、字符串统计

  print('hello'.count('l'))
  print('hello'.count('ll'))
  print(len('hello'))

在这里插入图片描述

4、字符串分离和连接

  #分离
  s = '172.25.254.250'
  s1 = s[::-1]
  print(s1)
  
  s1 = s.split('.')
  print(s1)
  s2 = s1[::-1]
  print(s1[::-1])

  date = '2019-06-23'
  date1 = date.split('-')
  print(date1)

  #连接
  print('-'.join(date1))
  print('.'.join(s2))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42566251/article/details/94036344
今日推荐