想做个爬虫小工具辅助工作,初学Python,写博客记录,加深理解。
<class ‘str’>,由单引号、双引号、三单引,三双引前后包起来的都算是str。如:
'hello,word' "hi,007" '''你好,世界!''' """3月芳菲"""
定义了字符串,接下来就是对它进行操作。首先要了解字符串是不可变型数据。
对字符串的操作方法很多,有些方法使用较多,也较重要。
1.str.index(), str.find()。在字符串中查找指定数据,返回其下标(索引)
两个方法区别是,find找不到返回数值-1,index找不到系统报错(ValueError: substring not found)
格式:
my_str.index(sub="", __start="",__end="")
my_str.find(sub="",__start="",__end="")
如:my_str = "abcd和ABCD"
print(my_str.find("AB"))
5
注:在str,list,tuple,range()中,第一个元素的下标都是从0开始计。
2.str.endwith(), str.startwith()。判断字符串是否是以指定的数据为结尾或开头,返回bool值。
my_str = "abcd-ABCD"
print(my_str.startswith("A"), my_str.endswith("D"))
False True
3.replace()。用指定数据去替换字符串中原有的数据
格式: my_str.replace(__old="",__new="",__count=)
my_str = "我是谁,我从哪里来,我要到哪里去?"
print(my_str, id(my_str))
new_str = my_str.replace("我", "I", 2)
print(new_str, id(new_str))
我是谁,我从哪里来,我要到哪里去? 1366704
I 是谁,I 从哪里来,我要到哪里去? 31570720
可见,字符串是不可变类型,被修改后,在内存中的存储位置都变化了。
4.str.splitlines(), str.split()。
前者以换行符分割字符串,后者以指定数据去分割字符串。返回的是一个列表。
格式:
my_str.split(sep="",maxsplit=int)
my_str.splitlines()
my_str = "oh, my god, what's wrong?"
print(my_str.split(sep=",",maxsplit=2 ))
my_str2 = "床前明月光,\n疑是地上霜。\n举头望明月,\n低头思故乡。"
print(my_str2.splitlines())
[‘oh’, ’ my god’, " what’s wrong?"]
[‘床前明月光,’, ‘疑是地上霜。’, ‘举头望明月,’, ‘低头思故乡。’]
5.str.partition(), str.rpartition().
前者根据指定数据把字符串分割成三部分。后者根据指定数据,从右边查找,把字符串分割成三部分。
my_str = "三国演义.txt.txt"
print(my_str.partition("."))
print(my_str.rpartition("."))
(‘三国演义’, ‘.’, ‘txt.txt’)
(‘三国演义.txt’, ‘.’, ‘txt’)
rpartition()很实用。因为最后一个后缀应该才是文件的真正类型。
对字符串的处理,有很多正-反顺序都可以进行的方法。
6.jion()
对字符串中的每一个元素用指定数据连接。
my_str = "my god,好险!"
print("+".join(my_str))
m+y+ +g+o+d+,+好+险+!
“+”号也可以连接字符串。感觉这种拼接方式在实际中更好用!
str1 = "哈哈,"
str2 = "就是这个范!"
print(str1 + str2)
哈哈,就是这个范!
7. str.isdigit(), 字符串有很多is打头的判断属性的方法。
my.isdigit() # => 纯数字。数字包括⑵ 和 ②
my.isalpha() # => 纯字母(包括汉字)
my.isalnum() # => 纯数字、纯字符、数字+字符三种情况都返回True。空格、符号都不行。
8. count(), len()
前者统计指定数据在字符串中总计出现的次数,后者返回指定字符串的长度。
str3 = "aababcabcdAABABCABCD"
print(str3.count("a"))
str4 = "hi,吃饭了吗?"
print(len(str4))
4
8
9.下标 ,不仅字符串使用,list,tuple使用得更频繁
字符串中,元素所处位置称为下标(索引),就是index()和find()中返回的值。Pyton中对字符串的操作方法,很多都可以通过使用下标指定范围,对范围内的字符串进行操作.如:index(), find(), replace(), count(), endwith(), startwith().
10, in, not in,判断指定数据是否存在指定字符串中。比遍历方便!
str5 = "Users/Administrator/Desktop"
print("top" not in str5)
print("top" in str5)
False
True
11.字符串从尾到头输出
my_str = "我是谁,我从哪里来,我要到哪里去?"
new_str = my_str[::-1]
print(new_str)
我是谁,我从哪里来,我要到哪里去?
?去里哪到要我,来里哪从我,谁是我
后记:有些没写下来,以后再来修改。有些是其他类型能用,并且用得更频繁的,字符串这里也没有提到。