python09字符串
字符串
类型1:str类型,用于内存中进行
类型2:bytes类型,用于储存在文件或者在网络上传输
>>> s="abc"
>>> type(s)
<class 'str'>
>>> s.encode("gbk") #结果丢弃了
b'abc'
>>> s=s.encode("gbk") #结果存到变量中以后可以使用
>>> type(s)
<class 'bytes'>
>>> s="finger cross"
>>> type(s)
<class 'str'>
>>>11min
判断一个变量是否是字符串类型
>>> a=1
>>> a=a+1
>>> a
2
>>> isinstance(a,str)
False
>>> isinstance("a",str)
True
>>> isinstance(b"a",bytes)
True
>>> isinstance(b"a",(str,bytes)) #表示变量是其中一种类型就可以
True
>>> isinstance("我h有点笨",str)
True
isinstance用在函数的类型判断中
def add(a,b):
if isinstance(a,int) and(b,int)
return a+b
print(add(1,1)) #2
print(add(1,"a")) #None
>>> a="好好学习"
>>> a='好好学习'
>>> a="""好
... 好
... 学
... 习"""
>>> a
'好\n好\n学\n习'
>>>"""保留格式,可以换行"""
三引号用来保留格式
>>> a="I am a \"a"
>>> a
'I am a "a'
>>> a="In's a boy!"
>>> a
"In's a boy!"
>>>单引号里带双引号或者双引号里带单引号就不需要转移符号/
>>> a='I am a \'a'
>>> a
"I am a 'a"
>>> a="a b"
>>> print(a)
a b
>>> a="a\tb" #t属于制表符,中间会间隔8个占位符
>>> print(a)
a b
>>> a="a\nb" #n为换行符
>>> print(a)
a
b
>>>r是回车符,打印最后一个,n是回车符
>>> a='a\rb'
>>> print(a)
b
>>>
>>> a="a\\b"
>>> print(a)
a\b
模板字符串,格式化输出
>>> s="my name is %s"%"Mike"
>>> print(s)
my name is Mike
>>> s="my number is %d"%100 #d是整数
>>> print(s)
my number is 100
>>> s="my number is %.1f"%1.23
>>> print(s)
my number is 1.2
>>> s="I am 80%% %s"%"lady"
>>> s
'I am 80% lady'
>>> s="my number is %.1f"%1.23
>>> print(s)
my number is 1.2
>>> s="I am 80%% %s"%"lady"
>>> s
'I am 80% lady'
>>> s="%%%f"%1.23
>>> s
'%1.230000'
>>> s="%%%.2f"%1.23
>>> s
'%1.23'
>>>遍历字符串
>>> s="MOney"
>>> for i in s:
... print(i)
...
M
O
n
e
y
>>>统计一个RockRoll,里面一共有几个O?
count=0
s="RockRoll"
for i in s :
if i =="o":
count+=1
print(count)
>>>统计一个RockRoll,里面O分别在哪个坐标和位置?
>>> s="RockRoll"
>>> result=[]
>>> for i in range(len(s)):
... if s[i]=="o":
... result.append(i)
...
>>> print(result)
[1, 5]
>>>
>>> s='abcdefg'
>>> print(s[2:5]) #取前不取尾
cde
>
>> s[0::2]
'aceg'
>>> s='abcdefg'
>>> s[0::3]
'adg'
>>> s[0::3]
'adg'
>>> s[-1]
'g'
>>> s[-1:-3:-1]
'gf'
>>> s[-1::-1] #字符串倒序输出
'gfedcba'
>>> s[-1::-2]
'geca'
切片可以越界不报错,切片是带:
>>> s[:]
'abcdefg'