python初入江湖2

字符串str

-用来表示一串文字信息
-表示:单引号,双引号,三引号(三单引号或三双引号,能够括起多行信息)
-单双引号交错使用
a="hello world"
print(a)
用引号表示 <a style="color:red"> 
`<a style="color:red">`

字符串方法:增

使用+

-str1+str2+str3
	a="hello "
	b="world"
	c=a+b
	print(c)  #  `hello world` 

join

a="".join("sdfa")
print(a)  #`sdfa`
a="ew"
b=a.join("1234")
print(b)  #`1ew2ew3ew4`

format

-"{}{}{}".format(obj1,obj2,obj3)
b="come"
c="on"
d="baby"
a="{} {} {}".format(b,c,d)
print(a)  `comeonbaby`
a1="{1} {2} {0}".format(d,b,c)
print(a1)  #`come on baby`
a2="{n0} {n1} {n2}".format(n0=b,n1=c,n2=d)
print(a2)  #`come on baby`

格式化字符%s

-"%s %s"%(str1,str2)
-%s是占位符
a="hi"
b="girl"
c="%s %s"%(a,b)
d="%s,%s"%(a,b)
print(c)  #`hi girl`
print(d)  #`hi,girl`

strip

-strip()是清除字符串首尾指定的字符或字符序列,默认是清除字符串两侧的空格或换行符
-lstrip()是清除字符串左侧的空格
-rstrip()是清除字符串右侧的空格
a=" hi girl!! "
b=a.strip()
print(b)  #`hi girl!!`
c=a.lstrip()
print(c)  #`hi girl!! `
d=a.rstrip()
print(d)  #` hi girl!!`
e=a.strip(!)
print(e)  #` hi girl `

replace

-把字符串中的字符或字符串替换新的字符或字符串,如果指定第三个参数max,则替换从左至右不超过max次
a="hi girl"
b=a.replace("hi","hello")
print(b)  #`hello girl`
c=a.replace("i","a")
print(c)  #`ha garl`

upper

-将字符串的小写字母全部改成大写字母,只能改字母,不能改数字
a="sdfgSfs"
b=a.upper()
print(b)  #`SDFGSFS`

lower

-将字符串的大写字母全部改成小写字母,只能改字母,不能改数字
a="sfSFDgsdf"
b=a.lower()
print(b)  #`sfsfdgsdf

capitalize

-字符串首字母改成大写
a="hello girl"
b=a.capitalize()
print(b)  #`Hello girl`

title

-将字符串标题化,即单词首字母大写,其余字母小写
a="hi GIRL"
b=a.title()
print(b)  #`Hi Girl`

count

-与列表方法相同,统计元素在str出现几次
a="sdfgwfsdf"
b=a.count("s")
print(b)  #2

find

-查找元素索引,没查到返回-1,查到返回元素索引位置
a="sdfgsdfwsf"
b=a.find("f")
c=a.find("n")
print(b)  #2
print(c)  #-1

type

-查看字符串类型
a="234"
type(a)=str

isdigit

-查看字符串是否是数字
a = "hello world"
b = a.isdigit()
print(b)  #false

isalpha

-查看字符串是否是字母
a = "hello world"
b = "helloworld"
c = a.isalpha()
d = b.isalpha()
print(a)  #false 因为中间有空格
print(b)  #true

startswith

-判断字符串是否以...为开头
a = "sdfsdesf"
b = a.startswith("sdf")
print(b)  #true

endswith

-判断字符串是否以...为结尾
a = "sdfsdesf"
b = a.startswith("f")
print(b)  #true

isupper

-判断字符串是否全是大写字母 	
a = "DFfgd" 	
b = a.isupper 	
print(b)  #false

islower

-判断字符串是否全是小写字母  
a = "DFfgd"  
b = a.islower  
print(b)  #false 

转义字符

-用一个特殊的方法表示出一系列不方便写出的内容,比如回车键,换行键,退格键
-借助反斜杠字符,一旦字符串中出现反斜杠,则反斜杠后面一个或多个字符表示已经不是原来的意思了,进行了转义

转义字符用法

-\\	反斜杠
-\`	单引号
-\"	双引号
-\	续航符
如:a = "lov\
       e"
       print(a)  #love
-\a	响铃,发出声音
-\b	退格(backspace)
-\e	转义

猜你喜欢

转载自blog.csdn.net/xiaogeldx/article/details/82908246
今日推荐