Python入门-字符串初相识

开发 后端
从本文开始准备介绍Python中的常见数据结构:字符串、列表、集合、字典。其中字符串、列表、字典应用非常频繁,需要重点掌握,本文介绍的是字符串及相关操作和方法。最后的字符串3种格式化方法将在下篇文章详细讲解。

[[412886]]

 本文转载自微信公众号「尤而小屋」,作者Peter。转载本文请联系尤而小屋公众号。

大家好,我是Peter呀~

从本文开始准备介绍Python中的常见数据结构:字符串、列表、集合、字典。其中字符串、列表、字典应用非常频繁,需要重点掌握,本文介绍的是字符串及相关操作和方法。最后的字符串3种格式化方法将在下篇文章详细讲解。

一、认识字符串

字符串在Python中是一种数据对象类型,用str表示,通常用单引号或者双引号包裹起来(英文的半角符号)

字符串string,是有零个或者多个字符组成的有限串行,通常记为s=a[1]a[2]...a[m]

  1. strings = "hello world"  # 双引号 
  2. strings 

'hello world'

  1. type(strings) 

str

  1. new_strings = 'hello python'  # 单引号 
  2. new_strings 

通过type函数查看类型

  1. type(new_strings)   

str

  1. type(100)  # 数值型 

int

  1. type("100")  # 字符串类型 

str

如果字符串本身内容就有引号,我们有两种解决方式:

  • 双引号包裹单引号
  • 使用转义字符
  1. # 如果字符串本身内容也包含引号 
  2. # 1、双引号包裹单引号 
  3.  
  4. x = "I'm Peter!" 

"I'm Peter!"

  1. # 使用转义字符\ 
  2.  
  3. y = 'I\'m Peter' 

"I'm Peter!"

  1. # 3、使用r“字符内容":原始字符串 
  2.  
  3. z = r"I'm Peter!" 

二、字符串基础操作

2.1键盘输入

键盘输入的任何内容都是字符串

  1. name = input("my name is: "

my name is: Peter

  1. name  # 返回的是字符串类型数据 

'Peter'

  1. # 键盘输入的都是字符串类型数据 
  2.  
  3. age = input("my age is: ")   

my age is: 20

  1. type(age)  # 返回的仍然是字符串 

str

2.2变量与字符串

python中有这样一句话:变量是无类型的,对象有类型

在下面的列子中,我们看到:变量x既可以是int类型,也可以是字符类型;但是数值5和字符串python都是有自己固定的数据类型。

  1. x = 5  # 变量x可以贴在int类型的数字5上:赋值语句 
  1. x  = "python"  # 变量x也可以贴在字符串类型上 
  1. # 通过赋值语句来表示变量和字符串对象之间的引用关系 
  2.  
  3. a = "hello-python" 

'hello-python'

  1. type(a) 

str

2.3查看字符串地址

  1. id(a) 

4516524144

  1. id(age) 

4516499824

2.4原始字符串

用r开头引起的字符串就是我们常用的原始字符串,放在里面的任何字符串都是表示它的原始含义,从此不需要转义

  1. s = "hello \npython" 
  2. print(s)  # 发生换行 

hello

python

  1. # 如何解决:1-使用转义字符 
  2. print("hello \\npython"

hello \npython

  1. # 2-使用r包裹起来 
  2. print(r"hello \npython"

hello \npython

三、索引和切片

索引和切片是python中非常重要的一个概念,记住几点:

  • 索引左边从0开始,右边从-1开始
  • 切片语法:start:end:step,step表示步长

3.1索引

使用的index()来查看某个字符的索引

  1. str1 = "python" 
  2. id(str1) 

4473172336

  1. str2 = "thonpy" 
  2. id(str2) 

4516506736

  1. # 寻找某个字符的索引index:索引从0开始 
  2.  
  3. str1.index("h"

3

  1. str1.index("n"

5

3.2切片

关于切片总结4点:

  • 标准形式:start:stop:step
  • 含头不含尾:包含start部分,不包含stop部分
  • 切片的时候,索引左边从0开始,右边从-1开始
  • 步长step可正可负
  1. str3 = "learn python" 
  2. str3 

'learn python'

  1. # 标准切割 
  2.  
  3. str3[0:4:1] # 步长为1 

'lear'

  1. str3[:4:1] # 开头的0可以省略 

'lear'

  1. str3[:4]  # 步长1也可以省略 

'lear'

  1. str3[0:4:2] # 步长为2 

'la'

  1. str3[:10]  # 步长为1,切到索引为10,不包含10 

'learn pyth'

  1. str3[10:0:-2] # 步长为2 

'otpna'

  1. str3.index("o")  # 从索引10的o字符开始切割,往前切 

10

四、字符串进阶操作

4.1求长度

  1. len(str3) 

12

4.2返回最值

每个字符都有自己对应的数字编码,通过比较数字就可以知道对应字符的大小

  1. max(str3)  # 根据ASCII码的取值来决定 

'y'

  1. min(str3) 

' '

  1. ord("y")  # 每个字符对应的编码 

121

  1. ord("z"

122

  1. ord(" ")   

32

  1. chr(121)   # 数值对应的字符:反编码的过程 

'y'

  1. "aa" > "ab"  # 第一个字符相同就比较第二个 

False

  1. "aac" > "aab"  # c 大于 b 

True

4.3判断是否存在

  1. "p" in str3 

True

  1. "q" in str3 

False

  1. str3 

'learn python'

4.4字符串重复

  1. str1 

'python'

  1. str1 * 3 

'pythonpythonpython'

4.5字符串连接

两种方式:

  • 通过+来实现
  • 通过join来实现
  1. str1 * 3 

'python'

  1. str4 = "learn "  # 后面有个空格 
  2. str4 

'learn '

  1. str4 + str1 

'learn python'

  1. "I" + " " + "am" + " Peter"  # 使用+号多次连接 

'I am Peter'

  1. join连接 
  2.  
  3. " ".join(("learn","python"))  # 连接符号为空格 

'learn python'

  1. "+".join(("learn","python"))  # 连接符号为+ 

'learn+python'

  1. " ".join(("I","am""Peter"))   

'I am Peter'

  1. 8 + "python"   # 不同类型的数据不能相加,看下面的报错 

---------------------------------------------------------------------------

  1. TypeError                                 Traceback (most recent call last
  2.  
  3. <ipython-input-56-d9d7a3d8267b> in <module> 
  4. ----> 1 8 + "python"   # 不同类型的数据不能相加 

TypeError Traceback (most recent call last) in ----> 1 8 + "python" # 不同类型的数据不能相加TypeError: unsupported operand type(s) for +: 'int' and 'str'

  1. "8" + "python" 

'8python'

  1. str(8) + "python"  # 使用str函数强制转换 

'8python'

五、常用字符串方法

5.1判读是否全部为字母

  1. "python".isalpha() 

True

  1. "8python".isalpha() 

False

5.2分割字符串

  1. str5 = "My name is Peter" 
  2. str5.split(" ")  # 通过空格进行分割,得到的是列表(后面会介绍列表) 

['My', 'name', 'is', 'Peter']

  1. str5.split()   # 默认是空格切割,效果同上 

['My', 'name', 'is', 'Peter']

  1. str5.split("")  # 报错空切割字符 

---------------------------------------------------------------------------

  1. ValueError                                Traceback (most recent call last
  2.  
  3. <ipython-input-63-e39a6d8acc4b> in <module> 
  4. ----> 1 str5.split("")  # 报错空切割字符 

ValueError: empty separator

  1. str5.split("is")   # 通过is来切割 

['My name ', ' Peter']

5.3去掉字符串的空格

  • strip():两端的空格
  • lstrip():左边的空格
  • rstrip():右边的空格
  1. str6 = " python "  # 左右各一个空格 
  2. str6 

' python '

  1. str6.strip() 

'python'

  1. str6.rstrip() 

' python'

  1. str6.lstrip() 

'python '

  1. str6   # 原来的值保持不变 

' python '

5.4字符大小写转化

python中实现各种类型的大小写转化

  • upper():字母全部转为大写
  • lower():字母全部转为小写
  • capitalize():首字母全部转为大写
  • title():字符串中所有单词的首字母大写,其他为小写
  • isupper():判断字母是否全部转为大写
  • islower():判断字母是否全部转为小写
  • istitle():判断是否为标题模式,即字符串中所有单词的首字母大写,其他为小写
  1. str7 = "this is Python"  # 只有P是大写 
  2. str7 

'this is Python'

  1. str7.upper()  # 全部为大写 

'THIS IS PYTHON'

  1. str7.lower()  # p也变成了小写 

'this is python'

  1. str7.capitalize()  # 首字母T大写 

'This is python'

  1. str7.islower()  # 是否全部为小写 

False

  1. str7.isupper()  # 是否全部为大写 

False

  1. str7.istitle()  # 是否为标题模式 

False

  1. str7.title() # 转成标题模式:每个单词的首字母大写 

'This Is Python'

总结

字符串在Python中是非常高频使用的是一种数据类型,从字符串的转化、获取字符串指定中的指定内容、字符串的切片索引等都是必须掌握的知识点,希望本文对读者有所帮助!

 

责任编辑:武晓燕 来源: 尤而小屋
相关推荐

2023-08-26 20:21:58

字符KotlinJava

2023-08-21 10:28:00

字符串字符Python

2022-05-18 11:35:17

Python字符串

2023-12-15 10:27:01

暴力匹配算法Python字符串

2010-03-09 16:16:55

Python字符串

2010-03-09 15:15:02

Python字符串类型

2020-08-11 14:29:31

Python字符串判断

2009-06-23 14:13:00

Java字符串

2024-04-01 08:41:39

字符串.NET

2010-02-01 16:22:36

Python字符串操作

2010-03-12 10:46:50

Python字符串

2017-01-17 15:47:18

2010-03-22 17:53:50

Python字符Python字符串

2010-09-09 11:48:00

SQL函数字符串

2009-07-16 17:01:09

Swing字符串

2011-08-10 18:47:18

Cocoa字符串

2023-01-11 16:49:13

MySQL数据库

2014-01-02 16:14:10

PostgreSQL字符串

2021-06-09 07:55:18

Python格式化字符串

2010-03-03 16:25:41

Python字符串显示
点赞
收藏

51CTO技术栈公众号