Python之字符串

  字符串是一种序列,可以使用索引,切片,加法,乘法等进行操作。但是字符串是不可变的,不能对它进行赋值操作。

  可以使用一对单引号、上引号或者一对三个双引号、一对三个单引号来表示字符串,如果字符串里还有双引号,外面就可以使用单引号。

  (1)使用单引号来表示字符串,如下:

strName='I am bo xiao yuan'
print(strName)

  (2)使用双引号来表示字符串,如下:

strName="I am bo xiao yuan"
print(strName)

  (3)使用三引号来表示字符串,此种方法可以在多行内显示字符串,三引号中可以使用单引号和双引号,如下:

strName = '''Hello,
I am bo
xiao
yuan.
what's your "name".
'''
print(strName)

  说明:

  • 在Python中,字符串之间可以使用+拼接成新的字符串;
  • 字符串变量可以和整数使用*重复拼接相同的字符串;
  • 数字和字符串之间不能进行其他运算,否则会报错。
first_name = "zhang"
last_name = "san"
num = "13"
print(first_name + last_name)
print(first_name * 20)
print(num + 1)  # 报错

  字符串里的转义字符 \

# \'  ==> 显示一个普通的单引号
# \"  ==> 显示一个普通的双引号
# \n  ==> 显示一个换行
# \t  ==> 显示一个制表符
# \\  ==> 显示一个普通的反斜线
x = 'I\' xiaoming'  # \表示的是转义字符,作用是对\后面的字符进行转义
 在字符串的钱满添加r,在Python里表示的是原生字符串
x = r'hello \teacher'
print(x)  # hello \teacher

1.1字符串的下标

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

  • 可迭代对象:str,list,tuple,dict,set,range都可以遍历。
  • str,list,tuple都可以通过下标来获取或者操作数据。
  • 在计算机里,下标都是从0开始的。
  • 字符串是不可变的数据类型,对于字符串的任何操作,都不会改变原有的字符串。

1.2字符串的切片

  切片方法适用于字符串,列表,元组。

  • 1)切片使用索引值来限定范围,从一个大的字符串中切除小的字符串。
  • 2)列表和元组都是有序的集合,都能够通过索引值获取对应的数据。
字符串[开始索引:结束索引:步长]
  • 指定的区间属于左闭右开型,从起始位开始,到结束为的前一位结束。
  • 从头开始,开始索引数字可以省略,冒号不能省略,到结尾结束,结束索引数字可以省略,冒号不能省略。
  • 步长默认为1,如果连续切片,数字和冒号都可以省略。
a = "0123456789"
print(a[:])  # 0123456789
print(a[3:])  # 3456789
print(a[:3])  # 012
print(a[3:5])  # 34
print(a[0:6:2])  # 024
print(a[2::-1])  # 210
print(a[::-1])  # 9876543210  逆序

1.3字符串常见方法

  字符串的常用操作方法,不会对原字符串进行任何操作,都是产生一个新的字符串。

1.3.1find

  mystr.find(str, start=0, end=len(mystr)),检查str是否包含在mystr中,如果是则返回开始的索引值,否则返回-1。

mystr = "hello world boxiaoyuan and bodayuan"
print(mystr.find("boxiaoyuan"))  # 12
print(mystr.find("boxiaoyuan", 0, 10))  # -1

1.3.2index

  mystr.index(str, start=0, end=len(mystr)),跟find()方法一样,只不过如果str不在mystr中会报异常。

mystr = "hello world boxiaoyuan and bodayuan"
print(mystr.index("boxiaoyuan"))  # 12
print(mystr.index("boxiaoyuan", 0, 10))  # -1

12
Traceback (most recent call last):
  File "E:/Python/01_Python基础/demo05.py", line 5, in <module>
    print(mystr.index("boxiaoyuan", 0, 10))  # -1
ValueError: substring not found

1.3.3count

  mystr.count(str, start=0, end=len(mystr)),返回str在start和end之间在mystr里面出现的次数。

mystr = "hello world boxiaoyuan and bodayuan"
print(mystr.count("yuan"))  # 2
print(mystr.count("yuan", 0, 10))  # 0

1.3.4replace

  mystr.replace(str1, str2,  mystr.count(str1)),把mystr 中的str1 替换成str2,如果count 指定,则替换不超过count 次。

mystr = "hello world boxiaoyuan and bodayuan"
replaced_str = mystr.replace("bo", "zhang")
print(replaced_str)  # hello world zhangxiaoyuan and zhangdayuan
replaced_str = mystr.replace("bo", "zhang", 1)
print(replaced_str)  # hello world zhangxiaoyuan and bodayuan

1.3.5split

  mystr.split(str=" ", maxsplit),以str为分隔符切片mystr,如果maxsplit有指定值,则仅分隔maxsplit个子字符串。

mystr = "hello world boxiaoyuan and bodayuan"
split_str = mystr.split(" ", 2)
print(split_str)  # ['hello', 'world', 'boxiaoyuan and bodayuan']

1.3.6capitalize

  mystr.capitalize(),把字符串的第一个字符大写。

my_str = "hello world boxiaoyuan and bodayuan"
cap_str = my_str.capitalize()
print(cap_str)  # Hello world boxiaoyuan and bodayuan

1.3.7title

  my_str.title(),把字符串的每个单词首字母大写。

my_str = "hello world boxiaoyuan and bodayuan"
title_str = my_str.title()
print(title_str)  # Hello World Boxiaoyuan And Bodayuan

1.3.8startswith

  mystr.startswith(prefix, start=None, end=None),检查字符串是否是以prefix开头, 是则返回True,否则返回False

my_str = "hello world boxiaoyuan and bodayuan"
print(my_str.startswith("hello"))  # True
print(my_str.startswith("world", 6,20))  # True

1.3.9endswith

  mystr.endswith(suffix, start=None, end=None),检查字符串是否是以prefix结尾, 是则返回True,否则返回False

my_str = "hello world boxiaoyuan and bodayuan"
print(my_str.endswith("bodayuan"))  # True
print(my_str.endswith("world", 0, 11))  # True

1.3.10lower

  mystr.lower(),转换mystr 中的小写字母为小写。

my_str = "hello world boxiaoyuan and bodayuan"
title_str = my_str.title()
print(title_str)  # Hello World Boxiaoyuan And Bodayuan
lower_str = title_str.lower()
print(lower_str)  # hello world boxiaoyuan and bodayuan

1.3.11upper

  mystr.upper(),转换mystr 中的小写字母为大写

my_str = "hello world boxiaoyuan and bodayuan"
upper_str = my_str.upper()
print(upper_str)  # HELLO WORLD BOXIAOYUAN AND BODAYUAN

1.3.12ljust

  mystr.ljust(width),返回一个原字符串左对齐,并使用空格填充至长度width的新字符串

my_str = "hello"
ljust_str = my_str.ljust(10)
print(ljust_str)  # "hello     "

1.3.13rjust

  mystr.rjust(width),返回一个原字符串右对齐,并使用空格填充至长度width的新字符串

my_str = "hello"
rjust_str = my_str.rjust(10)
print(rjust_str)  # "     hello"

1.3.14center

  mystr.center(width),返回一个原字符串居中,并使用空格填充至长度width的新字符串

my_str = "hello"
center_str = my_str.center(10)
print(center_str)  # "  hello   "
my_str = "hello"
center_str = my_str.center(10, "*")
print(center_str)  # "  hello   "# **hello***

1.3.15lstrip

  mystr.lstrip(),删除mystr 左边的空白字符

my_str = "   hello"
lstrip_str = my_str.lstrip()
print(lstrip_str)  # "hello"

1.3.16rstrip

  mystr.rstrip(),删除mystr 右边的空白字符

my_str = "hello   "
rstrip_str = my_str.rstrip()
print(rstrip_str)  # "hello"

1.3.17strip

  mystr.strip(),删除mystr 两边的空白字符

my_str = "   hello   "
strip_str = my_str.strip()
print(strip_str)  # "hello"

  也可以去除指定的字符

s4 = 'rre博r小w园qsd'
s5 = s4.strip('qrswed')
print(s5)  # 博r小w园

1.3.18rfind

  mystr.rfind(str, start=0,end=len(mystr)),类似于find()函数,不过是从右边开始查找

my_str = "hello world boxiaoyuan and bodayuan"
print(my_str.rfind("boda"))  # 27

1.3.19rindex

  mystr.rindex( str, start=0,end=len(mystr)),类似于index(),不过是从右边开始

my_str = "hello world boxiaoyuan and bodayuan"
print(my_str.rindex("boda"))  # 27
print(my_str.rindex("ceshi"))  #  报异常

1.3.20partition

  mystr.partition(str),把mystr以str分割成三部分,str前,str和str后

my_str = "hello world boxiaoyuan and bodayuan"
par_str = my_str.partition("bo")
print(par_str) # ('hello world ', 'bo', 'xiaoyuan and bodayuan')

1.3.21rpartition

  mystr.rpartition(str),类似于partition()函数,不过是从右边开始

my_str = "hello world boxiaoyuan and bodayuan"
par_str = my_str.rpartition("bo")
print(par_str)  # ('hello world boxiaoyuan and ', 'bo', 'dayuan')

1.3.22splitlines

  mystr.splitlines(),按照行分隔,返回一个包含各行作为元素的列表

my_str = """hello world
boxiaoyuan
and 
bodayuan
"""
print(my_str.splitlines())  # ['hello world', 'boxiaoyuan', 'and ', 'bodayuan']

1.3.23isalpha

  mystr.isalpha(),如果mystr所有字符都是字母则返回True,否则返回False

my_str = "abcd"
print(my_str.isalpha())  # True
my_str = "1234"
print(my_str.isalpha())  # False

1.3.24isdecimal

  mystr.isdecimal(),如果mystr只由十进制组成,则返回True,否则返回False

S = "runoob2016"
print(S.isdecimal())  # False

S = "23443434"
print(S.isdecimal())  # True

1.3.25isalnum

  mystr.isalnum(),如果mystr所有字符都是字母或数字则返回True,否则返回False

my_str = "abcd"
print(my_str.isalnum())  # True
my_str = "1234"
print(my_str.isalnum())  # True
my_str = "abcd1234"
print(my_str.isalnum())  # True

1.3.26isspace

  mystr.isspace(),如果mystr 中只包含空格,则返回True,否则返回False

my_str = "abcd"
print(my_str.isspace())  # False
my_str = "   "
print(my_str.isspace())  # True

1.3.27join

  mystr.join(str),str中每个字符后面插入mystr,构造出一个新的字符串

name = ["my", "english", "name", "is", "zhangsan"]
my_str = " "
new_name = my_str.join(name)
print(new_name)  # my english name is zhangsan

1.3.28swapcase

  对字符串的大小写字母进行转换。

S = "This Is String Example....WOW!!!"
print (S.swapcase())  # tHIS iS sTRING eXAMPLE....wow!!!

1.5格式化打印字符串

1.5.1%

 print ('我叫%s, 身高%scm'  % (name,height))   ** 传入的值为元组,依次填充
  • %s :占位符 str()  
  • %d-:十进制 整数
  • %x : 十六进制
  • %f  :浮点型

指定长度:

  • %5d     右对齐,不足左边补空格
  • %-5d    - 代表左对齐,不足右边默认补空格
  • %05d    右对齐,不足左边补0

浮点数:

  • %f   默认是输出6位有效数据, 会进行四舍五入
  • 指定小数点位数的输出 %.2f---保留小数点后2位
  • %4.8f'    4代表整个浮点数的长度,包括小数,只有当字符串的长度大于4位才起作用.不足4位空格补足,可以用%04.8使用0补足空格

1.5.2format

  format( *args, **kwargs),格式化字符串。

  • 1、通过字符串中的花括号{}来识别替换字段,从而完成字符串的格式化。
  • 2、替换的内容包括:字段名、格式说明符三部分,形式一般为:{字段名:格式说明符}

1.省略不写:花括号内省略不写,代表传递位置参数

  • 替换字段形式{}
  • 注意事项:花括号个数少于等于后面的位置参数的个数,多了会报错
# 用{}代表占位符,直接位置传参
 
print('我是{},喜欢{}!'.format('灭霸','打响指'))
# 我是灭霸,喜欢打响指!
 
# {}数量必须少于后面位置参数数量,不然报错
print('我是{},喜欢{},不喜欢{}。'.format('宙斯','放大抢人头','放空大','小短腿'))
 
print('我是{},喜欢{},不喜欢{}。'.format('宙斯','放大抢人头'))
# 报错误:IndexError: tuple index out of range

2.数字形式传参:通过位置索引值传递位置参数

  • 索引从整数0开始
  • 索引可以重复引用,输出
  • 索引可以不按照传输顺序
  • 索引数值就是后面位置参数放入一个元组来取值的过程,所以索引数值不能大于元组里面位置参数的最大索引值,否则报错
print('我身高{0},年龄正好{1},{2}长。'.format('180cm',18,'15cm'))
# 我身高180cm,年龄正好18,15cm长。
 
print('我身高{0},{0}不多不少,年龄正好{1}。'.format('180cm',18))
# 我身高180cm,180cm不多不少,年龄正好18。
 
print('我身高{1},{1}不多不少,年龄正好{0}。'.format('180cm',18))
# 我身高18,18不多不少,年龄正好180cm。
 
print('我身高{0},年龄正好{1},{2}长。'.format('180cm',18))
# IndexError: tuple index out of range
# 索引值大于format()内的最大位置数

3.变量名{关键字} 传递输出参数

  • 特别注意,关键字的变量名在参数那里无需加引号,同时{}里面引用直接填变量名。
print('我的名字叫{name},我其实是一名{career}!'.format(name='尹天仇',career='演员'))
# 我的名字叫尹天仇,我其实是一名演员!
 
print('我叫{name2},又名{name1},我弟弟叫{name3}!'.format(name1='至尊宝',name2='秦汉',name3='秦祥林'))
# 我叫秦汉,又名至尊宝,我弟弟叫秦祥林!

4.{}、{0}、{name}混合使用

  • 位置参数在前,关键字参数在后
  • 但注意!!{}不能与数字形式{0}同时使用,但可以和关键字参数同时使用
print('吹个{0},吹个{2},吹大了{1},玩{ball}!'.format('球','气球','大气球',ball='球球'))
# 吹个球,吹个大气球,吹大了气球,玩球球!
 
print('吹个{},吹大了{},玩{ball}!'.format('球','气球','大气球',ball='球球'))
# 吹个球,吹大了气球,玩球球!
 
print('吹个{0},吹大了{1},玩{ball}!'.format('球','气球','大气球',ball='球球'))
# 吹个球,吹大了气球,玩球球!
 
print('吹个{0},吹大了{},玩{ball}!'.format('球','气球','大气球',ball='球球'))
#报错 ValueError: cannot switch from manual field specification to automatic field numbering

5.使用元组和字典传参:

  • str.format()方法可以使用*元组和**字典的形式传参,可以混用。
  • 方法相当于*args和**kwargs打散传参,元组按位置或索引传参,字典按关键字传参(键)。
  • 位置参数、关键字参数、*元组、**字典也可以同时使用,但要注意位置参数在关键字参数前,*元组要在**字典前。
  • 使用元组或者字典格式化输出的形式就是相当于将元组和字典打散,变成位置参数们和关键字参数们然后按照前面的方法传参就行
print('我喜欢{},喜欢{},同时也喜欢{}!'.format(*('篮球','足球','观球')))
# 我喜欢篮球,喜欢足球,同时也喜欢观球!
print('我喜欢{0},喜欢{1},同时也喜欢{2}!'.format(*('篮球','足球','观球')))
# 我喜欢篮球,喜欢足球,同时也喜欢观球!
 
# 字典
print('{name}的女朋友是{gf},我也喜欢{gf}!'.format(**{'name':'钢铁侠','gf':'小辣椒'}))
# 钢铁侠的女朋友是小辣椒,我也喜欢小辣椒!
 
# 元组+字典
print('我是{beauty}的{1},我们都喜欢{0},请大家{2}!'\
      .format(*('球类','球迷','文明观球'),**{'beauty':'斯嘉丽约翰逊',}))
# 我是斯嘉丽约翰逊的球迷,我们都喜欢球类,请大家文明观球!
 
# 位置参数、关键字参数、元组、字典混合使用:
print('我是{name},好像{age}了 ^_^,在{0},等你哦!\n喜欢{1}、{2}和{3}。\n我的唯一 >>>:{only_one}\n我的小可爱 >>>: {love}!'\
      .format('武汉',name='苏光体',age=18,*('读书','健身','折腾数码'),**{'only_one':'杨林','love':'苏弘睿'}))
# 我是苏光体,好像18了 ^_^,在武汉,等你哦!
# 喜欢读书、健身和折腾数码。
# 我的唯一 >>>:杨林
# 我的小可爱 >>>: 苏弘睿!

6.对象参数格式化输出传值

  • formate还可以使用对象属性传参,这个对象可以是实例化的对象,也可以是列表、字典
# 对象属性传参
# 实例化对象:
class Dog:
    def __init__(self,name,speak):
        self.name=name
        self.speak=speak
 
dog1=Dog('小黄','汪汪汪')
print('我的{0.name}会{0.speak}。'.format(dog1))
# 我的小黄会汪汪汪。
 
# 文件对象
with open('text.txt','wb') as f:
    print('打开的文件名为:{0.name}'.format(f))
# 打开的文件名为:text.txt
 
# 列表、字典对象
print('I have a {0[0]} , I have a {0[1]} .'.format(['Apple','Pen']))
print('我叫{0[name]},{0[id]}就是我!'.format({'name':'阿星','id':'9527'}))
print('{1[name]}变成了{0[0]},藏进了{1[role]}的裤裆里,为什么不变{0[1]}而是{0[0]}呢?'.format(['葡萄','苹果'],{'name':'菩提老祖','role':'至尊宝'}))
# I have a Apple , I have a Pen .
# 我叫阿星,9527就是我!
# 菩提老祖变成了葡萄,藏进了至尊宝的裤裆里,为什么不变苹果而是葡萄呢?

7.格式说明符:规定传入参数字符的格式

# 格式限定符
# 它有着丰富的的“格式限定符”(语法是{}中带:号),比如:
# 填充与对齐
# 填充常跟对齐一起使用
# ^、<、>分别是居中、左对齐、右对齐,后面带宽度
# :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
print('{:>8}'.format('zhang'))  #     zhang 前面三个空格
print('{:0>8}'.format('zhang'))  # 000zhang
print('{:a<8}'.format('zhang'))  # zhangaaa
print('{:p^10}'.format('zhang'))  # ppzhangppp
# 精度与类型f
# 精度常跟类型f一起使用
print('{:.2f}'.format(31.31412))  # 31.31
# 其他类型
# 主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制
print('{:b}'.format(15))  # 1111
print('{:d}'.format(15))  # 15
print('{:o}'.format(15))  # 17
print('{:x}'.format(15))  # f
# 用逗号还能用来做金额的千位分隔符
print('{:,}'.format(123456789))  # 123,456,789

1.5.3格式化 f''

 python3.6 后的版本支持:

f'名字是:{name},年龄是:{age}'  
posted @ 2019-05-12 07:51  博小园  阅读(337)  评论(0编辑  收藏  举报
回到顶部