目录
1、字符串定义
字符串(str)是Python中的一种非常常用的数据类型,用来表示文本数据。字符串可以包含任何字符,包括字母、数字、符号、空格、换行符等;
str1 = 'hello world!' #可以使用单引号
str2 = "人生苦短,我学Python!" #也可以使用双引号
2、字符串的常用语法
2.1 基础操作
打印字符串中的某个字符
可以通过索引来访问字符串中的某个字符;注意:索引从前到后是从0开始的,从后向前是从-1开始
s = 'python'
print(s[0]) #输出"p",索引0表示第一个字符
print(s[-1]) #输出"n",索引-1表示最后一个字符
切片
切片可以获取字符串中的某一段
s = 'python'
print(s[0:3]) #输出"pyt",从索引0开始,到索引3结束,但不包括索引3
print(s[1:]) #输出"ython",从索引1开始,直到最后结束
print(s[:3]) #输出"pyt",从头开始,到索引3结束,但不包括索引3
字符串拼接
可以使用运算符 + 将多个字符串拼接为一个字符串
s1 = 'hello'
s2 = 'world'
print(s1 + s2) #输出 helloworld
print(s1 + ' ' + s2) #输出 hello world
print(s1 + s2 + s1) #输出 helloworldhello
字符串重复打印
使用运算符 * 可以使字符串批量输出
s = 'python'
p