1.字符串判断
>>> s="你好"
>>> type(s)
<class 'str'>
>>> isinstance(s,(str,bytes))
True
>>> def add(a,b):
... if (not isinstance(a,str)) or (not isinstance(b,str)):
... return None
... return a+b
...
>>> print(add(1,"hello"))
None
>>> print(add("hello","world"))
helloworld
bytes:用于网络传输。
>>> s=b"abc"
>>> type(s)
<class 'bytes'>
>>> s="你好"
>>> s=s.encode("gbk")
>>> type(s)
<class 'bytes'>
>>> s=s.decode("gbk")
>>> type(s)
<class 'str'>
2.转义字符
>>> s="ab\'c\"de"
>>> print(s)
ab'c"de
>>> s="ab\'c\"\\de"
>>> print(s)
ab'c"\de
#原意输出,加r
>>> path="e:\test.txt"
>>> print(path)
e: est.txt
>>> path=r"e:\test.txt"
>>> print(path)
e:\test.txt
>>> path="e:\\test.txt"
>>> print(path)
e:\test.txt
>>> s="""1
... 2
... 3
... 4
... 5
...
... "
...
... ""
... """
>>> s
'1\n2\n3\n4\n5\n\n"\n\n""\n'
>>> print(s)
1
2
3
4
5
"
""
>>> class P():
... def __str__(self):
... return "str"
... def __repr__(self):
... return "repr"
...
>>> p=P()
>>> print(p)
str
>>> repr(p)
'repr'
>>> p
repr
3.字符串运算
>>> s="hello "
>>> s1="world"
>>> s+s1
'hello world'
>>> s*10
'hello hello hello hello hello hello hello hello hello hello '
>>> s[1]
'e'
>>> s[7] #索引不可以越界
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[1:9] #切片可以越界
'ello '
>>> s[5::-2]
'fdb'
>>> s[-1::-2]
'fdb'
>>> s[::-2]
'fdb'
>>> "a" in s
True
>>> "as" in s
False
4.模板字符串
>>> print("name is %s" % "Lily")
name is Lily
>>> print("name is %s" % "XiaoMing")
name is XiaoMing
>>> print("name is %d" % 123)
name is 123
>>> print("name is %E" % 123)
name is 1.230000E+02
>>> print("name is %c" % 123)
name is {
%s:都可以
%d:digit,传入整数
%f:小数,(eg:%.2f,保留两位小数,4舍6入5看齐,奇进偶不进)
#其他字符串格式化方式
>>> from string import Template
>>> s=Template("Name is ${key1} and ${key2}")
>>> print(s.substitute(key2="Lily" ,key1="Xiaoming"))
Name is Xiaoming and Lily
字符串常用函数
1.strip():用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
>>> s=" boy boy "
>>> s.strip()
'boy boy'
>>> s=" boy boy****"
>>> s.strip("*")
' boy boy'
>>> s="**boy boy****"
>>> s.rstrip("*")
'**boy boy'
2.lower(),upper(),swapcase(),capotalize():大小写互换
>>> "AAbb".lower()
'aabb'
>>> "AAbb".upper()
'AABB'
>>> "AAbb".swapcase() #互换
'aaBB'
>>> "lily".capitalize() #首字母大写
'Lily'
string包里的capwords():每个首字母大写 = title()
>>> "abc def gh".title()
'Abc Def Gh'
>>> import string
>>> string.capwords("abc def gh")
'Abc Def Gh'
3.string包常用函数
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
' \t\n\r\x0b\x0c'
4.ljust()、rjust():返回一个原字符串左/右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。
center():居中
zifll():在右对齐,不足部分用0补足
>>> "abc".ljust(8,"*")
'abc*****'
>>> "abc".ljust(2,"*")
'abc'
>>> "abc".rjust(5,"*")
'**abc'
>>> "abc".center(5,"*")
'*abc*'
>>> "hello".zfill(20)
'000000000000000hello'
5.find():检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
-
str.find(str, beg=0, end=len(string))
>>> "hello world".find("l") #只找一次
2
>>> "hello world".find("l",5) #指定位置
9
>>> "hello world".find("e",5) #没找到返回-1
-1
>>> "hello world".find("e",1,5)
1
>>> "hello world".find("e",2,5)
-1
如果想找多个,可以通过正则的方式。
>>> import re
>>> re.findall("mnz","hello mnz worldmnz")
['mnz', 'mnz']
#找到,但是没有返回位置
def find_all(s,dest_str):
"""
用result列表储存所有找到的字符串位置
求dest_str长度:length
通过坐标遍历s
判断当前位置取切片,start:start+length==dest_str
把当前坐标放到一个result的列表中
需要将当前的坐标跳转到当前坐标+length位置,继续
"""
result=[]
start=0
length=len(dest_str)
while start<len(s):
if s[start:start+length]== dest_str:
result.append(start)
start+=length
else:
start+=1
return result
print(find_all("aaa aaa jifeaaa","aaa"))
#结果:[0, 4, 12]
6.index():该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
>>> "hello world".index("x")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> try:
... "hello world".index("x")
... except:
... print("查找内容不存在")
...
查找内容不存在
7.rfind() :返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
rindex()同上,找不到抛异常
>>> "hello world hello lily hello".rfind("hello")
23