字符串

# -*- coding: utf-8 -*-
# @Time    : 2019/11/7 10:18
# @Author  : John
# @Email   : 2398344557@qq.com
# @File    : 字符串.py
# @Software: PyCharm
  • 字符串的切片
import string
words = string.ascii_lowercase[:9]    # 切片输出前9个小写的ascii码
print(words)
# —— abcdefghi
print(words[3])
# —— d
print(words[2:4])
# —— cd
print(words[:])    # 默认返回整个字符串,但只是浅复制
# —— abcdefghi
print(words[::])    # 默认返回整个字符串,但只是浅复制
# —— abcdefghi
print(words[-2:])
# —— hi
print(words[-2:2])    # 啥都没,空值
#
print(words[::-1])
# —— ihgfedcba
  • 字符串中四个比较重要的操作方法(内置函数)
# ****strip()、split()、join()、replace()****
  • 字符串常用的操作方法
  1. 大小写处理:upper()和lower()
# 1. upper()和lower()
# 常用指数:***
str1 = 'www.NEUEDU.com'
str2 = str1.upper()    # 全部大写(已是大写的会直接输出无需处理)
print(str2)
# —— WWW.NEUEDU.COM
str3 = str1.lower()    # 全部小写(已是小写的会直接输出无需处理)
print(str3)
# —— www.neuedu.com
  1. 判断开头结尾:startswith()和startswith()
# 2. startswith(prefix, start, end)和startswith(suffix, start, end)
# 常用指数:***
str1 = 'www.eeeNEUEDU.com'
print(str1.startswith('www'))    # 判断是否以www开头
# —— True
print(str1.endswith('.com'))    # 判断是否以.com结尾
# —— True
print(str1.startswith('eee', 4, 6))    # 左闭右开
# —— False
  1. 查找元素:find()和index()
# 3. 查找元素:find(sub, _start, _end)和index(sub, _start, _end)
# 常用指数:****
str1 = 'www.eeeNEUEDU.com'
print(str1.find('h'))    # 寻找字符串中的h元素,找不到时返回负一
# —— -1
print(str1.find('w'))    # 从左边开始,获取指定元素首次出现的下标
# —— 0
print(str1.find('N'))
# —— 7
print(str1.find('NEUEDU'))    # 不会报错,但只会返回输入字符串中首字母首次出现的下标
# —— 7
print(str1.rfind('w'))    # 从右边开始,获取指定元素首次出现的下标
# —— 2
# ------------------------
# print(str1.index('h'))    # index找不到这个子串时会报错
# —— ValueError: substring not found
print(str1.index('w'))
# —— 0
print(str1.find('N'))
# —— 7
print(str1.index('NEUEDU'))    # 不会报错,但只会返回输入字符串中首字母首次出现的下标
# —— 7
print(str1.rindex('w'))    # 从右边开始,获取指定元素首次出现的下标
# —— 2
  1. 清除占位符:strip()
# 4. strip(chars):默认取出字符前后两端的空格、换行、tab
# # 常用指数:*****
str1 = '    \n .com \t    '    # 16=4+2+1+4+1+4
print(len(str1))
# —— 16
print(len(str1.strip()))    # 剩.com
# —— 4
str2 = 'aabbccddff'
str2 = str2.strip('aa')    # 删除指定的首字符串(指定为左端)
print(str2)
# —— bbccddff
str3 = 'aabbccddff'
str3 = str3.lstrip('ff')    # 删除指定的首字符串(指定为左端),没有时输出原字符串
print(str3)
# —— aabbccddff
str4 = 'aabbccddff'
str4 = str4.rstrip('ff')    # 删除指定的首字符串(指定为左端)
print(str4)
# —— aabbccdd
  1. 分隔成列表:split()和splitlines()
# 5. split(sep, maxsplit):把字符串分隔成列表,默认是以空格进行分割
# 常用指数:*****
str1 = 'life is short, use Pyhton.'
print(str1.split())    # 英文版的jieba分词,默认对空格进行分割
# —— ['life', 'is', 'short,', 'use', 'Pyhton.']
print(str1.split(','))    # 指定对逗号进行分割
# —— ['life is short', ' use Pyhton.']
str2 = 'life;is;short,;use;Pyhton,; '
print(str2.split(';', 3))    # 指定分割多少个
# —— ['life', 'is', 'short,', 'use;Pyhton,; ']
print(str2.split(';', 4))    # 指定分割多少个
# —— ['life', 'is', 'short,', 'use', 'Pyhton,; ']
print(str2.split(';', 5))    # 指定分割多少个
# —— ['life', 'is', 'short,', 'use', 'Pyhton,', ' ']
print(str2.split(';', 3)[0])
# —— life

# 14.splitlines():按照行分割,返回包含按照行分割的元素列表(和第五合并)
# 常用指数:**
str2 = 'www.\nwww.NEUEDU.com'
print(str2)
# —— www.NEUEDU.com
print(str2.splitlines())
# —— ['www.', 'www.NEUEDU.com']
  1. 把列表转换成字符串:join()
# 6. join(iterable):把列表转换成字符串
# 常用指数:*****
str1 = 'life is short, use Pyhton.'
list1 = str1.split()    # list1里面元素必须全是字符串
print(list1)
# —— ['life', 'is', 'short,', 'use', 'Pyhton.']
print(''.join(list1))    # 无缝连接
# —— lifeisshort,usePyhton.
print(' '.join(list1))    # 空格隔开
# —— life is short, use Pyhton.
print('_'.join(list1))
# —— life_is_short,_use_Pyhton.
print('//'.join(list1))
# —— life//is//short,//use//Pyhton.
  1. is系列
# 7. is系列
# 常用指数:***
name = 'Xuebi520'
print(name.isdigit())    # 判断所有的字符串是否为数字
# —— False
print(name.isalpha())    # 判断所有的字符串是否为字母
# —— False
print(name.isalnum())    # 判断所有的字符串是否为数字或者是字母
# —— True
print(name.islower())    # 判断所有的字符串是否为小写字母
# —— False
print(name.isupper())    # 判断所有的字符串是否为大写字母
# —— False
print(name.istitle())    # 判断所有的字符串是否为大写字母开头
# —— True
print(name.isspace())    # 判断所有的字符串是否为空白字符
# —— False
  1. 计算某个字符出现的次数:count()
# 8. count(x, _start, _end):计算某个字符出现的次数
# 常用指数:****
name = 'Xuebi7533'
print(name.count('3'))
# —— 2
  1. 替换指定的字符:replace()
# 9. replace(old, new, count):替换指定的字符
# 常用指数:*****
name = '7533Xuebi7533'
name2 = name.replace('7533', '')
print(name2)
# —— Xuebi
name3 = name.replace('7533', '', 1)    # 替换第一次出现的
print(name3)
# —— Xuebi7533
  1. 首字母大写:capitalize()
# 10. capitalize():首字母大写
# 常用指数:***
name = 'xuebi7533'
print(name.capitalize())
# —— xuebi7533
  1. 左中右对齐: ljuest()、center()、rjuest()
# 11. center(width, fillchar):将字符串居中
# 常用指数:**
# 参数可以设置字符串总长度,可以用*进行填充
name = 'xuebi7533'
print(name.center(20))
# ——      xuebi7533
print(name.center(20, '*'))
# —— *****xuebi7533******
print(len(name.center(20, '*')))
# —— 20
name2 = 'xuebi'
print(name2.center(20))
# ——        xuebi
print(name2.center(20, '*'))
# —— *******xuebi********
print(len(name2.center(20, '*')))
# —— 20

# 15. ljust()和rjust()    (和第11合并)
# 常用指数:**
str1 = 'neuedu'
print(len(str1))
# —— 6
print(str1.ljust(20, '*'))    # 左对齐
# —— neuedu**************
print(len(str1.ljust(20)))
# —— 20
print(str1.rjust(20, '*'))    # 右对齐
# —— **************neuedu
print(len(str1.rjust(20)))
# —— 20
  1. 非字母隔开的每个单词的首字母大写:title()
# 12. title():非字母隔开的每个单词的首字母大写
# 常用指数:*
name = 'xue bi, &w7533t=f'
print(name.title())
# —— Xue Bi, &W7533T=F
  1. 分割三部分:partition()
# 13. partition(sep):将一个字符串分割成三部分(前、中、后)
# 常用指数:**
str1 = 'www.www.NEUEDU.com'
print(str1.partition('www'))    # 返回的是元组
# —— ('', 'www', '.www.NEUEDU.com')
print(str1.rpartition('www'))
# —— ('www.', 'www', '.NEUEDU.com')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容