python
字符串
字符串用双引号或者单引号包裹
原始字符
在字符串前面加r
print(r"D:\one\tow\three")
相当于
print("D:\\one\\tow\\three")
把字符当成其原本的含义
长字符串
三引号字符串“”“内容“”“
三引号内的字符串可以自由换行,不用加\n
input
input用于输入,但是input返回的是字符串
数字类型
1.整形
2.浮点型
对字符串进行操作
x ="i Love You"
print(x.capitalize())
#第一个字母转为大写
print(x.casefold())
#转化为全是小写的字符串
x.title()
#将字符串中每个单词的首字母都变成大写,该单词其他字母都变成小写
x.swapcase()
#将字符串中所以大小写字母转换
x.upper()
#将所有字母都变成大写
x.lower()
#将所有字母都换成小写
x ="今天出太阳!"
print(x.center(14))
#center是将字符串居中,括号内的数字是总长度
print(x.ljust(14))
#左对齐
print(x.rjust(14))
#右对齐
print(x.zfill(15))
#在前面补充0
print(x.center(14,"h"))
#效果:hhhh今天出太阳!hhhh
查找字符串
x = "上海自来水来自海上"
print(x.count("海"))
print(x.count("海",0,5))
#第一个数字表示起始位置,第二个表示末尾位置
x.find("海")
print(x.find("海"))
#从左往右,找出下标(字符串中对应位置和索引一样,都是从零开始)
print(x.rfind("海"))
#从右往左,找出下标
替换字符串
#替换
x="今天天气不适合出去"
print(x.replace("今天","明天"))
#replace中第一个引号是表示要被替换的内容,后一个引号是要换成的内容
table=str.maketrans("ABCDEFG","1234566")
print("CDAB".translate(table))
#想要转换,首先要定义一个规则,再引用translate进行替换
判断字符串
x="多喝热水对身体好"
print(x.startswith("多"))
#结果:True(返回的是布尔值)
#starswith判断是否出现在起始位置
print(x.endswith("好"))
#starswith判断是否出现在末尾位置
print(x.startswith("我",1))
#返回值为false
#从索引值为1的地方开始
print(x.endswith("对",2,5))
#从起始位置到末位置判断,而且不包括两端点
#可以用元组来判断
x="她喜欢python"
if x.startswith(("你","我","她")):
print("总有人喜欢python")
#元组中有一个匹配的就返回ture
m="I love Python"
print(x.istitle())
#判断一个字符串中所有单词是否都以大写字母开头,其它字母都为小写
print(m.isupper())
#判断所有单词是否大写
print(m.upper().isupper())
#从左往右执行,返回值为ture
print(m.isalpha())
#判断是否全为单词,由于m中包含空格,空格属于字符,所有返回false
n=" "
#判断是否是一个空白字符
print(n.isspace())
v="close the door\n"
#判断字符中是否能全部输出
print(v.isprintable())
#为假,因为有转义字符
t="jio_jio"
print(t.isidentifier())
#判断是否是合法标识符
截取字符串
v=" 左边不要留空白".lstrip()
print(v)
n="右边不要留空白 ".rstrip()
print(n)
m=" 左右都不要留空白 ".strip()
print(m)
j="www.ilovefishc.com".lstrip("w")
print(j)
#从左边删掉对应字符
i="www.ilovefishc.com".rstrip(".com")
print(i)
#从右边删掉对应字符
#从一侧开始字母逐个匹配,遇到不能被删除的字母就停止
p="www.ilovefishc.com".removeprefix("www.")
print(p)
q="www.ilovefishc.com".removesuffix(".com")
print(q)
#踢掉一个指定的字符串
字符串的拆分与拼接
#拆分&拼接
w="www.ilovefish.com".partition(".")
print(w)
#('www', '.', 'ilovefish.com')
e="ilovefishc.com/python".rpartition("/")
print(e)
#('ilovefishc.com', '/', 'python')
#未加r是从左往右,加了r是从右往左
r="大学之道,在明明德".split(",")#中文逗号
#打包成列表返回
print(r)
#['大学之道', '在明明德']
t="修身,养性,治国,家齐".rsplit(",",1)#中文逗号
print(t)
#['修身,养性,治国', '家齐']
#拼接
g=".".join(["www","ilovefish","com"])
print(g)
#www.ilovefish.com
#用join来实现拼接
b=" ".join(["nihao","nihao"])
print(b)
字符串格式化
#格式化字符串
js="1+2={},2的平方是{},3的平方是{}".format(1+2,2*2,3*3*3)
print(js)
jh="{1}看到{0}十分害怕".format("ty","zy")
print(jh)
#zy看到ty十分害怕
符号选项
#另外一种格式化
q=f"今天又是忙碌的{1}天"
print(q)
#符号选项
n="{:+} {:-}".format(520,-250)
print(n)
#+520 -250
m="{:,}".format(1234)
print(m)
#1,234
s="{:_}".format(12345)
print(s)
#12_345
l="{:,}".format(1234567)
print(l)
#1,234,567
i="{:.2f}".format(3.1415)
print(i)
#保留小数点后两位
t="{:.6}".format("ilovestudy")
print(t)
#iloves 相当于截取的作用