Python基础 03----字符串


字符串的表示方式

普通的文本内容,用单引号或者双引号表示

  • 使用三个单引号、双引号定义的字符串可以包裹任意文本

转义字符

转义字符含义
\r当前文本移动到本行开头
\n换行
\t用来表示一个制表符
\代表一个反斜线字符 \
\‘显示一个单引号
"显示一个双引号

字符串的切片和下标

下标/索引

# 下标我们又称之为索引,表示第几个数据。

# 可迭代对象: str  list  tuple  dict  set  range  都可以遍历
# str list tuple 可以通过下标来获取或者操作数据

# 在计算机里,下标都是从 0 开始的。
word = 'zhangsan'  # 字符串:一个一个的字符串在一起
# 可以通过下标来获取或者修改指定位置的数据
print(word[4])

# 字符串是不可变的数据类型
# 对于字符串的任何操作,都不会改变原有的字符串!!!
# word[4] = 'x'

# 切片就是从字符串里复制一段指定的内容,生成一个新的字符串
m = 'abcdefghijklmnopqrstuvwxyz'
print(m[5])  # m[index] ==> 获取指定下标上的数据

# 切片语法  m[start:end:step]
# 包含start,不包含end
# step 指的是步长,理解为间隔。每隔 step-1 个取一次
# step 为负数,表示从右往左获取

print(m[2:9])  # 包含start,不包含end
print(m[2:])  # 如果只设置了start,会"截取"到最后
print(m[:9])  # 如果值设置了end,会从头开始"截取"

# 步长默认为 1
print(m[3:15:2])  # dfhjln
print(m[3:15:1])  # defghijklmno
# print(m[3:15:0])  # 步长不能为0
print('------------------')
# print(m[3:15:-1])  # 没有数据
print(m[15:3:-1])  # ponmlkjihgfe
print(m[::])  # abcdefghijklmnopqrstuvwxyz 从头到尾复制
print(m[::-1])  # zyxwvutsrqponmlkjihgfedcba

# start和end如果是负数,表示从右边数
print(m[-9:-5])  # rstu

遍历

  • while 遍历
msg = 'hello world'
i = 0
while i < len(msg):
    print(msg[i])
    i += 1
  • for 遍历
msg = 'hello world'
for x in msg:
    print(x)

字符串的常见操作

  • 在Python中,字符串是不可变类型,说有字符串的相关方法都不会改变原有的字符串,只会返回一个新的结果,在新的返回结果里保留执行后的结果

获取长度:len

a = 'abcdefghijklmn'
print(len(a))

查找内容:find, index, rfind, rindex

# 查找内容的相关方法 find/index/rfind/rindex
print(a.find('l'))  # 获取指定字符的下标第一次出现位置的下标

print(a.index('l'))

# index find 区别
print(a.index('p'))
print(a.find('p'))
# find 找不到元素会返回 -1 index会报错
# rfind/rindex 从右往左找

判断:startswith, endswith, isalpha, isdigit, isalnum, isspace

startswith

# 判断是否以指定内容开始

mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.startswith('今'))  # True
print(mystr.startswith('今日')) # False

endswith

# 判断是否以指定内容结束

mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.endswith('好风光')) #True
print(mystr.endswith('好日子')) #False

isalpha

# 判断字符串是否都是纯字母

mystr = 'hello'
print(mystr.isalpha())  # True
mystr = 'hello world'
print(mystr.isalpha()) # False 因为中间有空格

isdight

# 判断字符串是否是纯数字,只要出现非0-9的数字,就为False
mystr = '1234'
print(mystr.isdigit()) # True
mystr = '123.4'
print(mystr.isdigit()) # False
mystr = '-1234'
print(mystr.isdigit()) # False

isalnum

# 判断字符串是否由字母和数字组成,只要出现了非字母和数字,就为False
mystr = 'abcd'
print(mystr.isalnum())  # True
mystr = '1234'
print(mystr.isalnum()) # True
mystr = 'abcd1234'
print(mystr.isalnum()) # True
mystr = 'abcd1234_'
print(mystr.isalnum()) # False

计算出现次数: count

mystr = '今天天气好晴朗,处处好风光呀好风光'
print(mystr.count('好'))  # 3. '好'字出现三次

替换内容:replace

替换字符串中指定的内容,如果指定次数count,则替换不会超过count次。

mystr = '今天天气好晴朗,处处好风光呀好风光'
newstr = mystr.replace('好', '坏')
print(mystr)  # 今天天气好晴朗,处处好风光呀好风光  原字符串未改变!
print(newstr)  # 今天天气坏晴朗,处处坏风光呀坏风光 得到的新字符串里,'好'被修改成了'坏'

newstr = mystr.replace('好','坏',2)  # 指定了替换的次数
print(newstr) # 今天天气坏晴朗,处处坏风光呀好风光 只有两处的'好'被替换成了'坏'

切割字符串:split, rsplit, splitlines, partition, rpartition

split

# split
# split 将一个字符串切割为一个列表,两个参数,最后一个是最大分割数

# !!返回值是一个列表

mystr = '今天天气好晴朗,处处好风光呀好风光'
result = mystr.split() # 没有指定分隔符,默认使用空格,换行等空白字符进行分隔
print(result) #['今天天气好晴朗,处处好风光呀好风光'] 没有空白字符,所以,字符串未被分隔

result = mystr.split('好')  # 以 '好' 为分隔符
print(result) # ['今天天气', '晴朗,处处','风光呀,'风光']

result = mystr.split("好",2) # 以 '好' 为分隔符,最多切割成3份
print(result) # ['今天天气', '晴朗,处处', '风光呀好风光']

rsplit

# rsplit('-',2)是将最后两位的字符分隔成列表(从右往左分割)
# a = 'hey-you-must-be-happy'
# b = a.split('-')
# print(b)
#
# c = a.rsplit('-', 2)
# print(c)

splitlines

# 按行分割,返回一个包含每一行的元素作为列表

partition

a = 'abcdFeghj'
# partition 分为三部分 前面,分隔符 后面,分割之后是一个元组
print('abcdFeghj'.partition('F'))

repartition

类似于partition函数,从右往左开始

修改大小写:capitalize, title, upper, lower

upper

# # 修改大小写
# print('hello'.capitalize())
# # upper 全大写
# print('hello'.upper())

lower

# # lower 全小写
# print('hello'.lower())
# # title 每个单词的首字母大写
# print('hello'.title())

capitalize

第一个单词的首字母大写

title

每个单词的首字母大写

应用

# while True:
#     content = input('请输入内容,输入exit退出')
#     print('输入的内容是', content)
#     # 不区分大小写
#     # 通过lower把大写转为小写来判断,不论输入的字符是什么
#     if content.lower() == 'exit':
#         break

空格处理:ljust, rjust, center, lstrip, rstrip, strip

ljust

# ljust(width,fillchar) rjust center
# width长度 fillchar 填充字符,默认使用空格
# 让字符串以指定长度显示,如果长度不够,用空格补齐,默认在右边
# 超过了,输入什么打印什么
# print('Monday'.ljust(10, '-'))
# print('Monday'.rjust(12, '-'))

lstrip

# print('apple'.center(20, '='))

# lstrip 去除掉左边的空格
print('    apple   '.lstrip())

rstrip

# rstrip 去掉右边的空格
print('    apple   '.rstrip())

strip

# strip 去掉空格
print('    apple   '.strip())

字符串拼接: join

# 把参数进行遍历,取出参数中的每一项,然后加上指定的字符分隔
mystr = 'a'
print(mystr.join('hxmdq'))  #haxamadaq  把hxmd一个个取出,并在后面添加字符a. 最后的 q 保留,没有加 a
print(mystr.join(['hi','hello','good']))  #hiahelloagood


# 可以把列表或者元组快速的转变为字符串,并且以指定的字符分隔
txt = '_'
print(txt.join(['hi','hello','good'])) #hi_hello_good
print(txt.join(('good','hi','hello'))) #good_hi_hello

字符串的运算符
‘+’ 拼接字符串
字符串和数字之间是用乘法运算
字符串和数字之间做==运算
字符串之间比较运算,会逐个比较字符串的编码
不支持其他运算

字符集和编码

# ASCII --> Latin1--> Unicode编码

# 字符 --> 数字编码存在一个对应的关系
# 使用内置函数 chr 和 ord 可以查看数字和字符的对应的关系
# ord 获取字符对应的编码, chr根据编码获取对应的字符

print(ord('a'))


# GBK utf-8 BIG5

print('你'.encode('gbk'))


# encode 将字符串转换为指定编码集
# decode 将编码集转换成为对应的字符

成员运算符

in 和 not in 成员运算符

用于快速判断元素是否在指定的可迭代对象里
注意:身份运算符后面只能是一个可迭代对象

# in 和 not in 运算符
# 用来判断一个内容在可迭代对象中是否存在

word = 'hello'
a = input('请输入一个字符')
# for b in word:
#     if b == a:
#         print('你输入的内容存在')
#         break
# else:
#     print('你输入的内容不存在')

字符串的format方法

格式化打印字符串

# % 占位符表示格式化一个字符串

# %s --> 字符串占位符
# %d --> 整数的占位符
#  %nd --> 打印时,显示n位,如果不够在前面使用空格补全 - 在右边加空格
# %f --> 浮点数占位符
# %.nf -- > 保留小数点后n位
name = 'Tom'
age = 18
money = 15.2
print('我的名字是%s,年龄是%d,赚了%f' % (name, age, money))

print('%03d' % 6)
print('%6d' % 6)
print('%-3d' % 6)

format方法

# {} 占位

a = '{},{}'.format('张三', 19)
print(a)

# {数字} 根据数字的顺序进行填入

b = '{1},{0}'.format('张三', 19)
print(b)
# {变量名}
d = '{age},{name}'.format(age=19, name='ll')
print(d)

# 混合使用{数字} {变量}  注意 变量要写在后面
# {} {数字}不能混合使用
# 与列表配合使用
f = ['ll', '上海', '190']
# g = '我的名字是{},我来自{},身高{}'.format(f[0], f[1], f[2])#
g = '我的名字是{},我来自{},身高{}'.format(*f)
print(g)

# 与字典配合使用
info = {'name': 'll', 'age': 19, 'addr': '上海'}
h = '{name},{age},{addr}'.format(**info)
print(h)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值