字符串
1、意义:字符串是Python中最常用的数据类型,使用单引号(‘’)或双引号(“”)创建字符串
示例:
var = "Hello World!"
Python不支持单个字符类型(java的char),即一个字符也是字符串类型
截取子字符串:使用方括号[]来截取字符串,语法格式:变量[头下标:尾下标]
字符串格式化
将一个值插入到一个有字符串格式符%s的字符串中
print('%s今年 %d 岁!' %('小明',10))
字符串格式化符号:举例几个常用,
%c 格式化字符及其ASCLL码 %s 格式化字符串
%d 格式化整数 %f 格式化浮点数,可指定小数点后的精度
f-string 字面量格式化字符串
在Python 3.6版本之后添加,在此之前,使用的是%
f-string格式化字符串以f开头,后面跟着字符串,字符串的表达式用大括号{}包起来,它会将变量或表达式计算后的值替换进去,实例如下:
name = 'Runoob'
print('hello %s' % name)
print(f'hello {name}')
print(f'1+2= {1+2}')
w = {'name':'Runoob','url':'www.runoob.com'}
print(f'{w["name"]}的网址为:{w["url"]}')
使用f-string的方式更加简单,不用判断%s,%d;在3.8版本,可以使用=符号来拼接运算表达式与结果:
x = 1
print(f'{x+1=}')
结果:x+1=2
Python的字符串内建函数:
列举:
lower(),将字符串所有大写都转换成小写
print('AbC'.lower())
>>> abc
len():返回字符串长度
print(len('abc'))
>>> 3
replace():替换
str.replace(old,new[,max])
old:将被替换的子字符串
new :新字符串,用于替换old子字符串
max:可选字符串,替换不超过max次
str = "www.w3cschool.cc"
print("菜鸟教程旧地址:", str)
print("菜鸟教程新地址:", str.replace("w3cschool.cc", "runoob.com"))
str = "this is string example....wow!!!"
print(str.replace("is", "was", 3))
本系列的基础知识都是在菜鸟教程学习,如果想了解更多,可以去:https://www.runoob.com/