字符串运算符
以下
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 一样的语法。 |
字符串格式化符号%
符号 | 描述 |
---|---|
%c | char 格式化字符及其ASCII码 |
%s | String 格式化字符串 |
%d | decimalism格式化整数 |
%f | float 格式化浮点数字,可指定小数点后的精度 |
%u | unsigned 格式化无符号整型 |
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)
与字符串有关的内建函数
与字符串有关的内建函数,在这个页面最下面