1. 下标和切片
列表与元组支持下标索引好理解,字符串实际上就是字符的数组,所以也支持下标索引。

  • 下标

    如果想取出部分字符,那么可以通过下标的方法,(注意python中下标从 0 开始)

>>> name="abcde"
>>> print(name[0])#注意python中下标从 0 开始
a
>>> print(name[4])
e
>>> 
  • 切片
    -
    切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作。

切片的语法:[起始:结束:步长],注意分隔符号是”:”

注意:选取的区间属于左闭右开型,即从”起始”位开始,到”结束”位的前一位结束(不包含结束位本身)。

>>> print(name[0:3])#取 下标0~2 的字符
abc
>>> print(name[0:4])
abcd
>>> print(name[0:5])#取 下标0~4 的字符
abcde
>>> print(name[2:]) #取下标2(包括2)以后所有的字符
cde
>>> print(name[:2])#取下标2(不包括2)以前所有的字符
ab
>>> print(name[::2])#正向隔1位取字符
ace
>>> print(name[::-2])#反向隔1位取字符
eca

想一想:(面试题)给定一个字符串aStr, 请反转字符串

>>> name="aStr"
>>> print(name[::-1])
rtSa

2. 字符串常见操作
如有字符串mystr = ‘hello world itcast and itcastcpp’,以下是常见的操作
<1>find
检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1

>>> print(mystr.find("itcast"))
12
>>> print(mystr.find("itcast",0,11))
-1

<2>index
跟find()方法一样,只不过如果str不在 mystr中会报一个异常.

mystr.index(str, start=0, end=len(mystr))

>>> print(mystr.index("itcast",0,11))
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: substring not found

<3>count
返回 str在start和end之间 在 mystr里面出现的次数

mystr.count(str, start=0, end=len(mystr))

>>> print(mystr.count("itcast"))
2

<4>replace
把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

mystr.replace(str1, str2, mystr.count(str1))

>>> name="hello world ha ha"
>>> print(name.replace("ha","HA"))
hello world HA HA
>>> print(name.replace("ha","HA",1))
hello world HA ha

<5>split
以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串
分隔后的结果已列表展现
mystr.split(str=” “, 2)

str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
spilt()较为常用

>>> print(name.split(' '))
['hello', 'world', 'ha', 'ha']
>>> print(name.split(' ',2))#分隔出2个字符串,剩下的为一个子字符串
['hello', 'world', 'ha ha']
>>> print(name.split(' ',3))
['hello', 'world', 'ha', 'ha']
>>> print(name.split(' ',4))#个数超出时,不会报错
['hello', 'world', 'ha', 'ha']
>>> print(name.split(' ',5))
['hello', 'world', 'ha', 'ha']

<6>capitalize
把字符串的第一个字符大写

mystr.capitalize()

>>> print(name.capitalize())
Hello world ha ha

<7>title
把字符串的每个单词首字母大写

>>> print(name.title())
Hello World Ha Ha
>>> name1="Hello world"
>>> print(name1.title())
Hello World

<8>startswith
检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False

mystr.startswith(obj)

>>> print(mystr.startswith("hello"))
True
>>> print(mystr.startswith("Hello"))
False

<9>endswith
检查字符串是否以obj结束,如果是返回True,否则返回 False.

mystr.endswith(obj)
<10>lower
转换 mystr 中所有大写字符为小写

mystr.lower()

>>> name="HELLO World"
>>> print(name.lower())
hello world

<11>upper
转换 mystr 中的小写字母为大写

mystr.upper()
<12>ljust
返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串

mystr.ljust(width)

>>> name="hello"
>>> print(name.ljust(10))
hello
>>> name.ljust(10)
'hello     '

<13>rjust
返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串

mystr.rjust(width)
<14>center
返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

mystr.center(width)

>>> print(name.center(20)) hello
>>> name.center(20)

<15>lstrip
删除 mystr 左边的空白字符

mystr.lstrip()

>>> name="      hello      "
>>> print(name.lstrip())
hello
>>> name.lstrip()
'hello      '

<16>rstrip
删除 mystr 字符串末尾的空白字符

mystr.rstrip()
<17>strip
删除mystr字符串两端的空白字符

>>> print(name.strip())
hello
>>> name.strip()
'hello'

<18>rfind
类似于 find()函数,不过是从右边开始查找.

mystr.rfind(str, start=0,end=len(mystr) )

<19>rindex
类似于 index(),不过是从右边开始.

mystr.rindex( str, start=0,end=len(mystr))

<20>partition
把mystr以str分割成三部分,str前,str和str后

mystr.partition(str)

<21>rpartition
类似于 partition()函数,不过是从右边开始.

mystr.rpartition(str)

>>> mystr.partition("itcast")
('hello world ', 'itcast', ' and itcastcpp')
>>> mystr.rpartition("itcast")
('hello world itcast and ', 'itcast', 'cpp')

<22>splitlines
按照行分隔,返回一个包含各行作为元素的列表

>>> name="hello\nworld"
>>> print (name)
hello
world
>>> name.splitlines()
['hello', 'world']

<23>isalpha
如果 mystr 所有字符都是字母 则返回 True,否则返回 False

mystr.isalpha()

<24>isdigit
如果 mystr 只包含数字则返回 True 否则返回 False.
mystr.isdigit()

<25>isalnum
如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False

mystr.isalnum()

<26>isspace
如果 mystr 中只包含空格,则返回 True,否则返回 False.

mystr.isspace()

<27>join
mystr 中每个字符后面插入str,构造出一个新的字符串

mystr.join(str)

>>> str=" "
>>> list=["hello","world","haha","666"]
>>> str.join(list)
'hello world haha 666'
>>> str="_"
>>> str.join(list)
'hello_world_haha_666'

可以用于除去空白字符后生成新的字符串

>>> a="hello world"
>>> a.split()
['hello', 'world']
>>> "".join(a.split())
'helloworld

练习题1:如下字符串,含有空格和换行符,返回使用空格或者’\t’分割后的倒数第二个子串
test=”hello world \t ha he \nhei \nher”
以\t分割
newTest=test.split(“\t”)
print(newTest)
print(“以\t\t分割后的倒数第二个子串:%s”%newTest[len(newTest)-2])
以空格分割
newTest=test.split()
print(newTest)
print(“以空格分割后的倒数第二个子串:%s”%newTest[len(newTest)-2])
结果如下:
[‘hello world ‘, ’ ha he \nhei \nher’]
以\t 分割后的倒数第二个子串:hello world
[‘hello’, ‘world’, ‘ha’, ‘he’, ‘hei’, ‘her’]
以空格分割后的倒数第二个子串:hei

练习题2:”hello world” 字符串统计的结果为: h:1 e:1 l:3 o:2 d:1 r:1 w:1

方法1:
a="hello shanghai china"--去空格b=''.join(a.split())--创建空列表,用于存放去重后字符li=[]for i in b:if i not in li:li.append(i)for i in li:print("%s:%d"%(i,a.count(i)))方法2:
>>> string = 'hello world'
>>> { a:string.count(a) for a in set(string.replace(' ','')) }
{'h': 1, 'e': 1, 'w': 1, 'l': 3, 'o': 2, 'd': 1, 'r': 1}

【python基础】字符串总结相关推荐

  1. 重温Python基础——字符串

    哈喽,兄弟们, 本文带大家复习一下Python基础中的字符串,不知道大家还记得多少内容呢? 字符串 1.字符串就是一系列字符 在python中,用引号括起的都是字符串,其中引号可以是单的,也可以是双的 ...

  2. python 基础 字符串烧烤流程

    字符串详细解答及有关函数 表现形式 特殊情况的输出:转义字符 输入输出 读取与切片 字符串修改及删除 字符串常用函数解析 常用内置函数 大白话和你一起学python,最基础的内容,希望和大家一起学习, ...

  3. Python基础-字符串(字符串常用函数/操作/字符串遍历)

    字符串就是一串字符, 表示文本类型的数据, 可以用"一对双引号"或者'一对单引号'定义一个字符串, 字符串定义格式为 字符串变量名 = '字符串的文本内容' 常用函数/操作 获取字 ...

  4. Python基础——字符串的使用

    一.字符串的驻留机制   在Python中字符串是基本数据类型,是一个不可变的字符序列,即不具备增删改等操作.   什么叫字符串驻留机制?   仅保存一份相同且不可变字符串的方法,不同的值被存放在字符 ...

  5. python基础字符串(二)

    解释: 如何定义字符串,单引号和双引号,三个单引号. "\" 反斜杠是转义的意思 # 这里\n是换行 b = '''hhehe\nlala'''# 反斜杠的使用 c = " ...

  6. Python基础——字符串、列表、元组

    字符串常用方法 主要包括:replace.find.count.split.partition.upper.lower.strip.join.format - replace(old,new) 对字符 ...

  7. Python基础----字符串

    a = dir(str) print ('str常用的方法:') for i in a:if i[0] != '_':print (i) str常用的方法: capitalize casefold c ...

  8. python基础===字符串的制表,换行基础操作

    \n\t 制表符和换行符 >>> print("Languages:\n\tPython\n\tC\n\tJavaScript") Languages:Pytho ...

  9. python基础: 字符串操作

    字符串 定义: 使用引号括起来的一串字符 一对单引号.一对双引号.三对单引号.三对双引号 转义:使用 '\',使原来有特殊含义的字符变成普通字符,也可以在定义字符串的前面加一个'r' 字符串拼接 s1 ...

  10. Python基础----字符串填充的几种方法

    背景介绍 在有些时候,我们需要固定长度的字符串作为某些后续步骤的输入,但是手头的字符串很可能是变长的,因此在这种情况下,我们就需要使用某些方法对字符串进行填充,使其长度符合要求.下面介绍几种在pyth ...

最新文章

  1. Java程序员需要熟悉的库
  2. Deep Neural Networks的Tricks
  3. Maven 编译使用 rt.jar
  4. python 游戏 —— 汉诺塔(Hanoita)
  5. c#中的BeginInvoke和EndEndInvoke 摘要
  6. C# 3.0入门系列(三)
  7. django 实现linux运维管理平台
  8. cs寄存器 x86 特权模式_Windows操作系统管理进程和线程:内核模式和用户模式
  9. JavaScript的面向对象原理之原型链
  10. dm数据库 linux版下载,Linux (Unix )下DM的安装
  11. 【Redis学习10】好友关注---关注与取关,共同关注及关注推送
  12. 图像分割网络-M-Net
  13. Python-声明变量
  14. Webpack源码泄露
  15. asynchttpclient java_Java-Post方法在Android的AsyncHttpClient中不起作...
  16. VMware虚拟机安装Ubuntu22.04并配置网络
  17. 【Android 插件化】VirtualApp 接入 ( 在 VirtualApp 工程下创建 Module | 添加依赖 | 启动 VirtualApp 插件引擎 )
  18. [ctfshow]入门4
  19. 闵帆教授《论文写作》——心得体会
  20. 超简单JS延迟5秒加载方法代码

热门文章

  1. 来看看小夏の算法入门——前缀和差分
  2. Windows环境下的RTX实时操作系统学习记录
  3. 【领域驱动设计】四色建模法
  4. Ubuntu基本操作命令
  5. Mkv转MP4方法集合整理
  6. 百度前端笔试题 css3画三角形
  7. 卫星监测“America”级#两#栖#攻#击#舰#(LHA-6)出港
  8. ExcelVBA之更改文件路径
  9. Word2Vec源码解析
  10. 高级复制解决冲突用DBMS_RECTIFIER_DIFF.RECTIFY出现的问题