>>> s="abc"
>>> type(s)
<class 'str'>
>>> s.encode("gbk")
b'abc'
>>>
>>> s=s.encode("gbk")
>>> type(s)
<class 'bytes'>
>>> s="中国"
>>> type(s)
<class 'str'>
1.单引号/双引号/三引号
>>> a="加油"
>>> a='加油'
>>> a="""加
... 油
... 少
... 年"""
>>> a
'加\n油\n少\n年'
#双引号里面打印引号:加\
>>> a="hello\"world"
>>> a
'hello"world'
2.\t和\n,\r,\
>>> a="a\tb"
>>> print(a)
a b
>>> a="a\nb" #换行符
>>> print(a)
a
b
>>> a="a\rb\rhello" #\r回车符,用得少
>>> print(a) #显示最后的内容
hello
#查看操作系统的回车符
>>> import os
>>> os.linesep
'\r\n'
#输出\
>>> a="a\\b"
>>> print(a)
a\b
3.模板字符串
>>> s="my name is %s and gender is %s" %("wang","F")
>>> s
'my name is wang and gender is F'
#当使用模板字符串时想打印%,需要写%%
>>> s="90%% %s" %"boy"
>>> s
'90% boy'
>>> s="%d%% boy" %90
>>> s
'90% boy'
- %s:百无禁忌
- %d:必须是整数
- %f:必须是浮点数。%。1f:表示保留一位小数
>>> s="test:%.1f" %1.365
>>> s
'test:1.4'
其余两种方式:
>>> from string import Template
>>> a=Template('would it be the ${key1} when we meet in ${key2}')
>>> a.substitute(key1='same',key2='heaven')
'would it be the same when we meet in heaven'
>>> "{0},your {1}".format("hello", "world")
'hello,your world'
4.遍历字符串
>>> s="gloryroad"
>>> for i in s: #穷举
... print(i)
...
#基于坐标
>>> for i in range(len("hello")):
#取值,不要越界
>>> s
'helloworld'
>>> s[-1]
'd'
>>> s[-2]
'l'
>>> s[0]
'h'
>>> s[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
练习:统计“helloworld”中几个“o”
>>> result=0
>>> for i in "helloword":
... if i=="o":
... result+=1
...
>>> print (result)
2
#统计“helloworld”中出现“o”的位置
>>> s="helloworld"
>>> for i in range(len(s)):
... if s[i]=="o":
... print("在第%d位置出现o" %(i+1))
...
在第5位置出现o
在第7位置出现o
*切片(有“:”):
>>> s
'helloworld'
>>> s[:2] #取2位置之前所有的字符串,不包含2位置
'he'
>>> s[3:5] #取从3到5之前,不包含5
'lo'
>>> s[1::2] #步长
'elwrd'
>>> s[::3]
'hlod'
#逆序
>>> s[-1:-3:-1]
'dl'
>>> s[-3:-1]
'rl'
>>> s[-1:-3:-2]
'd'
>>> s[-1::-1]
'dlrowolleh'
5.修改字符串