Fork me on GitHub

python入门-1-字符串初相识

python入门-字符串初相识

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

一、认识字符串

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

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

1
2
strings = "hello world"  # 双引号
strings
'hello world'
1
type(strings)
str
1
2
new_strings = 'hello python'  # 单引号
new_strings
'hello python'

通过type函数查看类型

1
type(new_strings)
str
1
type(100)  # 数值型
int
1
type("100")  # 字符串类型
str

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

  • 双引号包裹单引号
  • 使用转义字符
1
2
3
4
5
# 如果字符串本身内容也包含引号
# 1、双引号包裹单引号

x = "I'm Peter!"
x
"I'm Peter!"
1
2
3
4
# 使用转义字符\

y = 'I\'m Peter'
y
"I'm Peter"
1
2
3
4
# 3、使用r“字符内容":原始字符串

z = r"I'm Peter!"
z
"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中有这样一句话:变量是无类型的,对象有类型

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

a = "hello-python"
a
'hello-python'
1
type(a)
str

2.3查看字符串地址

1
id(a)
4516524144
1
id(age)
4516499824

2.4原始字符串

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

1
2
s = "hello \npython"
print(s) # 发生换行
hello
python
1
2
# 如何解决:1-使用转义字符
print("hello \\npython")
hello \npython
1
2
# 2-使用r包裹起来
print(r"hello \npython")
hello \npython

三、索引和切片

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

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

3.1索引

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

1
2
str1 = "python"
id(str1)
4473172336
1
2
str2 = "thonpy"
id(str2)
4516506736
1
2
3
# 寻找某个字符的索引index:索引从0开始

str1.index("h")
3
1
str1.index("n")
5

3.2切片

关于切片总结4点:

  • 标准形式:start:stop:step
  • 含头不含尾:包含start部分,不包含stop部分
  • 切片的时候,索引左边从0开始,右边从-1开始
  • 步长step可正可负
1
2
str3 = "learn python"
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
'python'
1
2
str4 = "learn "  # 后面有个空格
str4
'learn '
1
str4 + str1
'learn python'
1
"I" + " " + "am" + " Peter"  # 使用+号多次连接
'I am Peter'
1
2
3
# join连接

" ".join(("learn","python")) # 连接符号为空格
'learn python'
1
"+".join(("learn","python"))  # 连接符号为+
'learn+python'
1
" ".join(("I","am", "Peter"))
'I am Peter'
1
8 + "python"   # 不同类型的数据不能相加
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-56-d9d7a3d8267b> in <module>
----> 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
2
str5 = "My name is Peter"
str5.split(" ") # 通过空格进行分割,得到的是列表(后面会介绍列表)
['My', 'name', 'is', 'Peter']
1
str5.split()   # 默认是空格切割,效果同上
['My', 'name', 'is', 'Peter']
1
str5.split("")  # 报错空切割字符
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-63-e39a6d8acc4b> in <module>
----> 1 str5.split("")  # 报错空切割字符


ValueError: empty separator
1
str5.split("is")   # 通过is来切割
['My name ', ' Peter']

5.3去掉字符串的空格

  • strip():两端的空格
  • lstrip():左边的空格
  • rstrip():右边的空格
1
2
str6 = " python "  # 左右各一个空格
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
2
str7 = "this is Python"  # 只有P是大写
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中是非常高频使用的是一种数据类型,从字符串的转化、获取字符串指定中的指定内容、字符串的切片索引等都是必须掌握的知识点,希望本文对读者有所帮助!

本文标题:python入门-1-字符串初相识

发布时间:2021年07月31日 - 16:07

原始链接:http://www.renpeter.cn/2021/07/31/python%E5%85%A5%E9%97%A8-1-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%88%9D%E7%9B%B8%E8%AF%86.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea