python(七)Str

字符串运算符

以下

a = "hello "
b = "Python"
操作符描述实例
+字符串连接 a + b 输出结果Hello Python
*重复输出字符串 a*2 输出结果HelloHello
[]通过索引获取字符串中字符 a[1]输出结果 e
[ : ]截取字符串中的一部分,遵循左闭右开原则,str[0,2] 是不包含第 3 个字符的。 a[1:4] 输出结果ell
in成员运算符 - 如果字符串中包含给定的字符返回 True‘H’ in a 输出结果 True
not in成员运算符 - 如果字符串中不包含给定的字符返回 True‘M’ not in a 输出结果 True
r/R原始字符串,所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。print( r’\n’ ) print( R’\n’ )
%格式字符串与 C 中函数 sprintf 一样的语法。

字符串格式化符号%

符号描述
%cchar 格式化字符及其ASCII码
%sString 格式化字符串
%ddecimalism格式化整数
%ffloat 格式化浮点数字,可指定小数点后的精度
%uunsigned 格式化无符号整型

format

基本语法是通过 {} 和 : 来代替以前的 % 。

参数个数、类型可以不受限

 s = "{} is a {}, he is {} years old".format("ssh", "student", 22)
print(s) #ssh is a student, he is 22 years old

参数顺序可以打乱

s = "{1} is a {0}, he is {2} years old".format("student", "ssh", 22)
print(s) #ssh is a student, he is 22 years old

参数可以设置

普通设置

s = "{name} is a {grade}, he is {age} years old".format(name = "ssh", grade = "student", age = 22)
print(s) #ssh is a student, he is 22 years old

或者 字典设置

me = {
    "name": "ssh",
    "grade": "student",
    "age": 22
}
s = "{name} is a {grade}, he is {age} years old".format(**me)
print(s) #ssh is a student, he is 22 years old

或者 列表设置

me = ["ssh", "student", 22]
s = "{0[0]} is a {0[1]}, he is {0[2]} years old".format(me)
print(s) #ssh is a student, he is 22 years old

数字格式化

数组也是填充在 {} 内的
为了方便,这是我自己定义的

字母表示
x没有字符的字符位,使用何种字符来填充
y数字占几个字符位
z是哪一种类型的数字(整型、二进制一类的)

可以组合使用

字符含义
:要填充的数字的格式
yz表示这个数字要占y个字符位
.yf表示小数点以后要占y个字符位
^yz居中
x<yz左对齐
x>yz右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+表示在正数前显示 +,(负数前面当然显示 -)
-负数前显示-(废话,负数前面当然得显示-,才能表明这是负数),但正数前面不会显示+;
(空格)表示在正数前加空格
b、d、o、x分别是二进制、十进制、八进制、十六进制。
l = [x for x in range(-10, 10)]
# < 左对齐
for x in l:
    print("this is {:-<5d}".format(x))

在这里插入图片描述

# > 右对齐
for x in l:
    print("this is {:0>5d}".format(x))

在这里插入图片描述

# ^ 居中对齐
for x in l:
    print("this is {:^5d}".format(x))

在这里插入图片描述

# +
print("this is {:+b}".format(l[16])) #this is +110
# -
print("this is {:-d}".format(l[1])) #this is -9
# .yf
print("{:.3f}".format(3.1415926)) #3.142

三引号(单双引都行)

输出的为所见即所得

s = '''
45  1
  444'''
ss = """
fdfff   f   f"""
print(s)
print(ss)

在这里插入图片描述

与字符串有关的内建函数

与字符串有关的内建函数,在这个页面最下面

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值