这里是一段防爬虫文本,请读者忽略。
本文原创首发于CSDN,作者IDYS
博客首页:https://blog.csdn.net/weixin_41633902/
本文链接:https://blog.csdn.net/weixin_41633902/article/details/107386815
未经授权,禁止转载!恶意转载,后果自负!尊重原创,远离剽窃!
Python3
起,字符串就是Unicode
类型print('"mysql\t Oracle"')
print("'mysql\t Oracle'")
print('''this is test "" \t\t 12''')
print(r'who\t\tam')
print(R'WHO\t\t\n am')
print('how are you \\t')
"mysql Oracle"
'mysql Oracle'
this is test "" 12
who\t\tam
WHO\t\t\n am
how are you \t
注意:在字符串前面加上r 前缀相当于将字符串里面的所有字符当作普通字符,这也就意味着转义字符和特殊字符都将当作普通字符
Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用
字符串是一个可迭代对象,所以其可以用list()
函数转化成一个新的列表对象
str1 = 'who are you'
print(str1)
print(type(str1))
for i in str1:
print(i, end='\t') #即使是单个字符,python也会将其当作字符串处理
print(type(i))
print(str1[1:4]) #左闭右开区间,会访问1,2,3字符串,4不会访问
print(str1[4:-1]) #访问从四开始到倒数第二个字符串
print(str1[4:])
list1 = list(str1) #这代表字符串为可迭代对象
print(list1)
print(type(list1))
who are you
w
h
o
a
r
e
y
o
u
ho
are yo
are you
['w', 'h', 'o', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u']
"string".join(iterable) -> str
举例
str1 = 'golden'
print("\t$\t".join(str1))
list1 = ['12', '3', '5']
print(' '.join(list1))
try:
list2 = ['1', [2, 3], '5'] #可迭代对象本身含有列表[2, 3],所以会类型报错
print(' '.join(list2))
except TypeError:
print("类型错误")
try:
list3 = ['2', ['3', '4'], '5'] #可迭代对象本身含有列表['3', '4'],所以会类型报错
print(' '.join(list3))
except TypeError:
print("类型错误")
g $ o $ l $ d $ e $ n
12 3 5
类型错误
类型错误
+ -> str
2
个字符串连接在一起* -> str
举例
print('a' + 'r')
print("who " * 3)
ar
who who who
split
系
partition
系
split(sep=None, maxsplit=-1) -> list of strings
sep
指定分割字符串,缺省的情况下空白字符串作为分隔符maxsplit
指定分割的次数,-1
表示遍历整个字符串举例
str1 = 'who am i , i am your best friends'
print(str1.split()) # 按照空白字符切割
print(str1.split("am")) # 按照 am 切割
print(str1.split('y')) # 按照 y 切割
print(str1.split(' ')) # 按照空白字符切割
print(str1.split(' ', 2)) # 按照空白字符切割,切割两次分为三段
print(str1.split(' ', 3)) # 按照空白字符切割,切割三次分为四段
['who', 'am', 'i', ',', 'i', 'am', 'your', 'best', 'friends']
['who ', ' i , i ', ' your best friends']
['who am i , i am ', 'our best friends']
['who', 'am', 'i', ',', 'i', 'am', 'your', 'best', 'friends']
['who', 'am', 'i , i am your best friends']
['who', 'am', 'i', ', i am your best friends']
rsplit(sep=None, maxsplit=-1) -> list of strings
sep
指定分割字符串,缺省的情况下空白字符串作为分隔符maxsplit
指定分割的次数,-1
表示遍历整个字符串虽然切割顺序是从右到左,但是排序还是从左到右
str1 = 'who am i , i am your best friends'
# 以下切割顺序都是从右边到左,不过,排序顺序还是从左到右
print(str1.rsplit()) # 按照空白字符切割
print(str1.rsplit("am")) # 按照 am 切割
print(str1.rsplit('y')) # 按照 y 切割
print(str1.rsplit(' ')) # 按照空白字符切割
print(str1.rsplit(' ', 2)) # 按照空白字符切割,切割两次分为三段
print(str1.rsplit(' ', 3)) # 按照空白字符切割,切割三次分为四段
['who', 'am', 'i', ',', 'i', 'am', 'your', 'best', 'friends']
['who ', ' i , i ', ' your best friends']
['who am i , i am ', 'our best friends']
['who', 'am', 'i', ',', 'i', 'am', 'your', 'best', 'friends']
['who am i , i am your', 'best', 'friends']
['who am i , i am', 'your', 'best', 'friends']
splitlines([keepends]) -> list of strings
keepends
指的是是否保留行分隔符\n
、\r\n
、\r
等print('my \n\r name \r call \r\n me by \n name and '.splitlines())
print('my \n\r name \r call \r\n me by \n name and '.splitlines(True))
str1 = '''your name
is idys
idys is
great
'''
print(str1.splitlines())
print(str1.splitlines(True))
['my ', '', ' name ', ' call ', ' me by ', ' name and ']
['my \n', '\r', ' name \r', ' call \r\n', ' me by \n', ' name and ']
['your name', 'is idys', 'idys is ', 'great']
['your name\n', 'is idys\n', 'idys is \n', 'great\n']
partition(sep) -> (head, sep, tail)
sep
分割字符串,必须指定str1 = 'who are you , the best student? is it?'
print(str1.partition(' '))
print(str1.partition('are'))
print(str1.partition('b'))
print(str1.partition('great'))
('who', ' ', 'are you , the best student? is it?')
('who ', 'are', ' you , the best student? is it?')
('who are you , the ', 'b', 'est student? is it?')
('who are you , the best student? is it?', '', '')
rpartition(sep) -> (head, sep, tail)
str1 = 'who are you , the best student? is it?'
print(str1.rpartition(' '))
print(str1.rpartition('are'))
print(str1.rpartition('b'))
print(str1.rpartition('great'))
('who are you , the best student? is', ' ', 'it?')
('who ', 'are', ' you , the best student? is it?')
('who are you , the ', 'b', 'est student? is it?')
('', '', 'who are you , the best student? is it?')
转义字符 | 描述 |
---|---|
\(在行尾时) |
续行符 |
\\ |
反斜杠符号 |
\' |
单引号 |
\" |
双引号 |
\a |
响铃 |
\b |
退格(Backspace) |
\000 |
空 |
\n |
换行 |
\v |
纵向制表符 |
\t |
横向制表符 |
\r |
回车 |
\f |
换页 |
\oyy |
八进制数,yy 代表的字符,例如:\o12 代表换行,其中 o 是字母,不是数字 0 。 |
\xyy |
十六进制数,yy 代表的字符,例如:\x0a 代表换行 |
\other |
其它的字符以普通格式输出 |
操作符 | 描述 |
---|---|
+ |
字符串连接 |
* |
重复输出字符串 |
[] |
通过索引获取字符串中字符 |
[:] |
截取字符串中的一部分,遵循左闭右开原则,str[0:2] 是不包含第 3 个字符的。 |
in |
成员运算符 - 如果字符串中包含给定的字符返回 True |
not in |
成员运算符 - 如果字符串中不包含给定的字符返回 True |
r/R |
原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 |
% |
格式字符串 |
符 号 | 描述 |
---|---|
%c |
格式化字符及其ASCII码 |
%s |
格式化字符串 |
%d |
格式化整数 |
%u |
格式化无符号整型 |
%o |
格式化无符号八进制数 |
%x |
格式化无符号十六进制数 |
%X |
格式化无符号十六进制数(大写) |
%f |
格式化浮点数字,可指定小数点后的精度 |
%e |
用科学计数法格式化浮点数 |
%E |
作用同%e,用科学计数法格式化浮点数 |
%g |
%f和%e的简写 |
%G |
%f 和 %E 的简写 |
%p |
用十六进制数格式化变量的地址 |
符号 | 功能 |
---|---|
* |
定义宽度或者小数点精度 |
- |
用做左对齐 |
+ |
在正数前面显示加号( + ) |
|
在正数前面显示空格 |
# |
在八进制数前面显示零('0') ,在十六进制前面显示'0x' 或者'0X' (取决于用的是'x' 还是'X' ) |
0 |
显示的数字前面填充'0' 而不是默认的空格 |
% |
'%%' 输出一个单一的'%' |
(var) |
映射变量(字典参数) |
m.n. |
m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) |
f-string
是 python3.6
之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。之前我们习惯用百分号 (%)
:
f-string
格式化字符串以 f
开头,后面跟着字符串,字符串中的表达式用大括号 {}
包起来,它会将变量或表达式计算后的值替换进去,实例如下
a = [1, 2, 3, 4, 5]
a_dict = {
"name":"idys", "age":24 }
print(f'你好 {a[2]}')
print(f'{2 * 5}')
print(f'123 {a_dict["name"]}')
你好 3
10
123 idys
upper()
lower()
swapcase()
注意:这些函数并不会改变字符串的值,而是会将值转化,返回新的对象
a = 'qqWEiNiDyS'
print("*********")
print(a.lower())
print("*********")
print(a) # a的值不变
print("*********")
print(a.upper())
print("*********")
print(a) # a的值不变
print("*********")
print(a.swapcase())
print("*********")
print(a) # a的值不变
*********
qqweinidys
*********
qqWEiNiDyS
*********
QQWEINIDYS
*********
qqWEiNiDyS
*********
QQweInIdYs
*********
qqWEiNiDyS
title() -> str
capitalize() -> str
center(width[, fillchar]) -> str
width
打印宽度fillchar
填充的字符zfill(width) -> str
width
打印宽度,居右,左边用0填充ljust(width[, fillchar]) -> str
左对齐rjust(width[, fillchar]) -> str
右对齐str1 = "I'm a student. My name is idys"
print(str1.title())
print(str1.capitalize())
print(str1.center(50, '0'))
print(str1.center(60, '^'))
print(str1.zfill(70))
print(str1.ljust(70, '^'))
print(str1.rjust(70, '^'))
I'M A Student. My Name Is Idys
I'm a student. my name is idys
0000000000I'm a student. My name is idys0000000000
^^^^^^^^^^^^^^^I'm a student. My name is idys^^^^^^^^^^^^^^^
0000000000000000000000000000000000000000I'm a student. My name is idys
I'm a student. My name is idys^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^I'm a student. My name is idys
replace(old, new[, count]) -> str
count
表示替换几次,不指定就是全部替换例子
url = "www.idayuanshuai.com"
print(url.replace("w", "e"))
print(url.replace("w", "e", 2))
print(url.replace("w", "me"))
print(url.replace("idayuanshuai", "idys"))
eee.idayuanshuai.com
eew.idayuanshuai.com
mememe.idayuanshuai.com
www.idys.com
strip([chars]) -> str
chars
中的所有字符chars
没有指定,去除两端的空白字符lstrip([chars]) -> str
rstrip([chars]) -> str
words = 'I LOVE dog, dog is cute . it is so lovely '
print(words.strip())
print(words.strip('I'))
print(words.rstrip())
print(words.lstrip('I L'))
I LOVE dog, dog is cute . it is so lovely
LOVE dog, dog is cute . it is so lovely
I LOVE dog, dog is cute . it is so lovely
OVE dog, dog is cute . it is so lovely
find(sub[, start[, end]]) -> int
在指定的区间[start, end)
,从左至右,查找子串sub
。找到返回索引,没找到返回-1rfind(sub[, start[, end]]) -> int
在指定的区间[start, end)
,从右至左,查找子串sub
。找到返回索引,没找到返回-1
演示
description = 'I am so so so so so so handsome'
print(description.find("so", 5))
print(description.find("so", 10, 14))
print(description.find("handsome", -10))
print(description.find('so'))
print(description.rfind('so'))
5
11
23
5
27
index(sub[, start[, end]]) -> int
[start, end)
,从左至右,查找子串sub
。找到返回索引,没找到抛出异常ValueError
rindex(sub[, start[, end]]) -> int
[start, end)
,从左至右,查找子串sub
。找到返回索引,没找到抛出异常ValueError
演示
description = 'idys is so so so so good'
print(description.index("so"))
print(description.index("so", 13))
print(description.index("so", 15, 20))
print(description.rindex('so', 1, 10))
print(description.rindex('so'))
8
14
17
8
17
index
和count
方法都是O(n)len(string)
count(sub[, start[, end]]) -> int
[start, end)
,从左至右,统计子串sub
出现的次数演示
description = 'idys is so so so so good'
print(description.count('so'))
print(description.count('so', -10))
print(description.count("so", 10))
4
2
3
endswith(suffix[, start[, end]]) -> bool
[start, end)
,字符串是否是suffix
结尾startswith(prefix[, start[, end]]) -> bool
[start, end)
,字符串是否是prefix
开头words = "i am very very very very like like like you"
print('1\t', words.startswith("i"))
print('2\t', words.startswith(' '))
print('3\t', words.startswith('am', 2))
print('4\t', words.endswith("you"))
print('5\t', words.endswith("very", 5, 9))
print('6\t', words.endswith("very", 5, 8))
1 True
2 False
3 True
4 True
5 True
6 False
isalnum() -> bool
是否是字母和数字组成isalpha() 是否是字母
isdecimal()
是否只包含十进制数字isdigit()
是否全部数字(0~9)isidentifier()
是不是字母和下划线开头,其他都是字母、数字、下划线islower()
是否都是小写isupper()
是否全部大写isspace()
是否只包含空白字符join
拼接只能使用分隔符,且要求被拼接的是可迭代对象+
拼接字符串还算方便,但是非字符串需要先转换为字符串才能拼接2.5
版本之前,只能使用printf style
风格的print
输出
printf-style formatting
,来自于C语言的printf
函数%
和格式字符组成,例如%s
、%d
等s
调用str()
,r
会调用repr()
。所有对象都可以被这两个转换%03d
表示打印3
个位置,不够前面补零format % values
,格式字符串和被格式的值之间使用%分隔values
只能是一个对象,或是一个和格式字符串占位符数目相等的元组,或一个字典printf-style formatting
举例import math
print("%+010d" % 321)
print("%+010d" % -321)
print("%-10d" % 321)
print("%10d" % 321)
print("%+010.5f" % math.pi)
print("%-010.5f" % math.pi)
print("%010.5f" % math.pi)
print("%10.5f" % math.pi)
+000000321
-000000321
321
321
+003.14159
3.14159
0003.14159
3.14159
format
函数格式字符串语法——Python鼓励使用
"{} {xxx}".format(*args, **kwargs) -> str
args
是位置参数,是一个元组
kwargs
是关键字参数,是一个字典
花括号表示占位符
{}
表示按照顺序匹配位置参数,{n}
表示取位置参数索引为n
的值
{xxx}
表示在关键字参数中搜索名称一致的
{ {}}
表示打印花括号
print("{}.{}.{}:{}".format('www', 'idayuanshuai', 'com', 80))
print("{}.{}.{}".format('www', 'idayuanshuai', 'com', 80))
# 这种方法自动把'www' 放入第一个{}, 'idayuanshuai' 放入第二个{} , 'com' 放入第二个,没有直接的话,自动按照顺序放入
www.idayuanshuai.com:80
www.idayuanshuai.com
print("{header}:{url}:{0}".format(80, header='https://', url='www.idayuanshuai.com'))
print("{header}.{hostname}.{domin}:{0}".format(80, header='https://', hostname='www', domin='idayuanshuai.com'))
https://:www.idayuanshuai.com:80
https://.www.idayuanshuai.com:80
注意:关键字参数需要放在位置参数后面
print('name:{0[name]}\tage:{0[age]}'.format({
"name": 'idys', "age": 18}))
print('{0[0]}\t{0[1]}'.format(('golden', 80)))
name:idys age:18
golden 80
from collections import namedtuple
Point = namedtuple("Point", 'x y')
p = Point(4, 5)
print(p)
print(p.x, p.y)
print('{
{
{0.x},{0.y}}}'.format(p))
print('{0.x}\t{0.y}'.format(p))
Point(x=4, y=5)
4 5
{4,5}
4 5
format
使用数字 | 格式 | 输出 | 描述 |
---|---|---|---|
3.1415926 |
{:.2f} |
3.14 |
保留小数点后两位 |
3.1415926 |
{:+.2f} |
+3.14 |
带符号保留小数点后两位 |
-1 |
{:+.2f} |
-1.00 |
带符号保留小数点后两位 |
2.71828 |
{:.0f} |
3 |
不带小数 |
5 |
{:0>2d} |
05 |
数字补零 (填充左边, 宽度为2) |
5 |
{:x<4d} |
5xxx |
数字补x (填充右边, 宽度为4) |
10 |
{:x<4d} |
10xx |
数字补x (填充右边, 宽度为4) |
1000000 |
{:,} |
1,000,000 |
以逗号分隔的数字格式 |
0.25 |
{:.2%} |
25.00% |
百分比格式 |
1000000000 |
{:.2e} |
1.00e+09 |
指数记法 |
13 |
{:>10d} |
13 |
右对齐 (默认, 宽度为10) |
13 |
{:<10d} |
13 |
左对齐 (宽度为10) |
13 |
{:^10d} |
13 |
中间对齐 (宽度为10) |
^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
b
、d
、o
、x
分别是二进制、十进制、八进制、十六进制。
print('{0}*{1}={2:<2}'.format(5, 3, 3*5))
print('{0}*{1}={2:<02}'.format(5, 3, 3*5))
print('{0}*{1}={2:<05}'.format(5, 3, 3*5))
print('{0}*{1}={2:>02}'.format(5, 3, 3*5))
print('{0}*{1}={2:&>10}'.format(5, 3, 3*5))
print('{:^30}'.format('centered'))
print('{:*^30}'.format('centered'))
5*3=15
5*3=15
5*3=15000
5*3=15
5*3=&&&&&&&&15
centered
***********centered***********
input
接收用户输入,接收类型为字符串strip
去掉首尾空格isdigit()
判断输入是否含有非法字符len
判断用户是否输入,同时可以判断有几位数reverse
反转,将数从个位往上输出
def judge_bit():
while True:
num = input("请输入,一个数字")
num = num.strip()
if len(num) == 0:
print("您的输入为空,请重新输入")
if not num.isdigit():
print("您的输入含有非法字符,请重新输入")
else:
break
dict1 = {
}
for i in num:
dict1.setdefault(i, num.count(i))
for k in dict1:
print("数字{0:5}重复{1:3}次".format(k, dict1[k]))
list1 = list(num)
list1.reverse()
count = 1
for i in list1:
print("第{}位\t为{:5}".format(count, i))
count += 1
if __name__ == "__main__":
judge_bit()
请输入,一个数字fdsfgs
您的输入含有非法字符,请重新输入
请输入,一个数字 1893451290
数字1 重复 2次
数字8 重复 1次
数字9 重复 2次
数字3 重复 1次
数字4 重复 1次
数字5 重复 1次
数字2 重复 1次
数字0 重复 1次
第1位 为0
第2位 为9
第3位 为2
第4位 为1
第5位 为5
第6位 为4
第7位 为3
第8位 为9
第9位 为8
第10位为1
isdigit()
函数只是识别字符串是否只含有数字,倘若用户输入一个负数,或者用户输入一个带有’+'号的整数,那么isdigit()
变无法判断这个是一个数字,所以本次采用正则表达式的方法re.search(r'^[+-]?\d+$', num)
,对用户输入进行限制,这样用户便只能输入整数len
求长度时,需要减一sort
方法对数字排序import re
def my_problem():
num = int(input_num("请输入你想输入的数字个数\n"))
count = 1
list1 = []
while count <= num:
swap_num = int(input_num("请输入第{}个数字{}".format(count, '\n')))
list1.append(swap_num)
count += 1
print("")
count = 1
for i in list1:
if i >= 0:
print("第{:}个数字为{:<20d}位数为{:^4d}".format(count, i, len(str(i))))
else:
print("第{:}个数字为{:<20d}位数为{:^4d}".format(count, i, len(str(i))-1))
count += 1
list1.sort()
print("")
print("数字从小到大排序依次为:")
count = 1
for i in list1:
print("{:+010d}".format(i), end="\t")
if count % 5 == 0:
print("")
count += 1
def input_num(s):
while True:
num = input(s)
num = num.strip()
if len(num) == 0:
print("num is zero, please input again")
elif not re.search(r'^[+-]?\d+$', num):
print("your input not fit the demand")
else:
break
return num
if __name__ == "__main__":
my_problem()
请输入你想输入的数字个数
6
请输入第1个数字
1241
请输入第2个数字
-23423
请输入第3个数字
+2342
请输入第4个数字
-234
请输入第5个数字
1324
请输入第6个数字
345
第1个数字为1241 位数为 4
第2个数字为-23423 位数为 5
第3个数字为2342 位数为 4
第4个数字为-234 位数为 3
第5个数字为1324 位数为 4
第6个数字为345 位数为 3
数字从小到大排序依次为:
-000023423 -000000234 +000000345 +000001241 +000001324
+000002342