字符串
- 单引号或双引号定义字符串变量
str1 = 'hello world'
str2 = "hello world"
print(type(str1)) # <class 'str'>
print(type(str2)) # <class 'str'>
- 三个引号定义字符串变量
str3 = '''hello world!'''
print(str3)
print(type(str3)) # <class 'str'>
print('-' * 20)
str4 = """hello world!"""
print(str4)
print(type(str4)) # <class 'str'>
- 字符串中有单引号时,使用单引号定义字符串,需要加
\进行转义
str5 = 'I\'am Tom'
print(str5) # 输出为I'am Tom
字符串切片
序列名称[开始位置下标:结束位置下标:步长(步阶)]
number = '0123456789'
number[0:3:1] # 012 => range方法非常类似,步长:每次前进1步
number[0:3:2] # 02 => 每次前进2步
步长可以为负数,正数代表从左向右截取,负数代表从右向左截取,默认步长为1
字符串中的查找方法
-
find()方法
检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则返回-1。
-
index()方法
检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则报异常。
字符串的修改方法
| 编号 | 函数 | 作用 |
|---|---|---|
| 1 | replace() | 返回替换后的字符串 |
| 2 | split() | 返回切割后的列表序列 |
| 3 | title() | 所有单词首字母大写 |
| 4 | upper()与lower() | 返回全部大写或小写的字符串 |
-
replace()方法
字符串.replace(要替换的内容, 替换后的内容, 替换的次数-可以省略)
str1 = 'hello world and hello world'
# 把字符串中所有world字符替换为python
print(str1.replace('world', 'python'))
# 把字符串中的第一个world进行替换为python
print(str1.replace('world', 'python', 1))
# 把and字符串替换为&&
print(str1.replace('and', '&&'))
-
split()方法
作用:对字符串进行切割操作,返回一个list()列表类型的数据
str1 = 'apple-banana-orange'
print(str1.split('-')) # 输出['apple', 'banana', 'orange']
print(str1) # 输出 'apple-banana-orange'
str2=str1.split('-')
print(str2) # 输出['apple', 'banana', 'orange']
-
join()方法
作用:和split()方法正好相反,其主要功能是把序列拼接为字符串
字符串.join(数据序列)
list1 = ['apple', 'banana', 'orange']
print('-'.join(list1)) # 输出'apple-banana-orange'
list2='-'.join(list1)
print(list2) # 输出'apple-banana-orange'
print(list1) # 输出['apple', 'banana', 'orange']
-
upper()与lower() 方法
upper():把字符串全部转换为大写形式
lower():把字符串全部转换为小写形式
字符串的判断方法
| 编号 | 函数 | 作用 |
|---|---|---|
| 1 | startswith() | 检查字符串是否是以指定子串开头,是则返回 True,否则返回 False。如果设置开始和结束位置下标,则在指定范围内检查。 |
| 2 | endswith() | 检查字符串是否是以指定子串结尾,是则返回 True,否则返回 False。如果设置开始和结束位置下标,则在指定范围内检查。 |
-
startswith()
作用:检查字符串是否是以指定子串结尾,是则返回 True,否则返回 False。如果设置开始和结束位置下标,则在指定范围内检查。
str1 = 'python program'
print(str1.startswith('python')) # 输出 True
-
endswith()
作用:检查字符串是否是以指定子串结尾,是则返回 True,否则返回 False。如果设置开始和结束位置下标,则在指定范围内检查。
str2 = 'photoimg.png'
print(str2.endswith('.png')) # 输出 True