首页 >> 大全

python学习1-数字、字符串、变量

2023-11-17 大全 32 作者:考证青年

目录

保留的关键字:

* 复制字符

[ ]提取字符:

():

分片(切片):

len()函数:

split()函数:

join()函数:

()函数:

()函数:

find()函数:

rfind()函数:

count():

():

strip():

():

title():

upper():

lower():

():

():

type(thing)   #获取thing的数据类型

变量名只能包含:小写字母、大写字母、数字、下划线,不能以数字开头

保留的关键字:

['False', 'None', 'True', '', 'and', 'as', '', 'async', 'await', 'break', 'class', '', 'def', 'del', 'elif', 'else', '', '', 'for', 'from', '', 'if', '', 'in', 'is', '', '', 'not', 'or', 'pass', 'raise', '', 'try', 'while', 'with', 'yield']

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

>>> divmod(9,5)    #同时得到9//5和9%5
(1, 4)

// 运算后面的小数部分是被舍去的(不是四舍五入)。

>>> 9/5
1.8
>>> 9//5
1
>>> 9%5
4
>>> 5%9
5
>>>

int()函数类型转换时,浮点数后面的小数部分会被舍去(不是四舍五入)。

>>> int(1.8)
1

字符串是不可变的,不能对原字符串修改,可以将字符串一部分复制到新字符串修改。

三元引号'''/""" 用于创建多行字符串。

>>> str1 = '''
... first
... second
... last'''
>>> str1
'\nfirst\nsecond\nlast'

\n换行符,\t制表符,\" \'输出" ';

>>> print("\'")
'
>>> print("\"")
"

+进行字符串拼接,字符串中间不会自动添加空格,print函数会在不同参数之间添加空格,结尾添加换行符;

>>> "a"+"b"
'ab'
>>> print("a"+"b")
ab
>>> print("a","b")
a b
>>> a = 1
>>> b = 2
>>> print(a,b,"hhh")
1 2 hhh

* 复制字符

>>> start = "Na"
>>> middle = "hey"
>>> print(start*3,middle*2)
NaNaNa heyhey
>>> end = "bye"+"\n"
>>> print(start*3,middle*2,end)
NaNaNa heyhey bye>>> print(start*3,middle*2,end,"....")
NaNaNa heyhey bye....
>>> str2 = "hhh1"*4
>>> str2
'hhh1hhh1hhh1hhh1'

[ ]提取字符:

偏移量从左到右0-n,从右到左-1- -n

():

改变字符串函数

分片(切片):

[start:end:step] [起始偏移量:终止偏移量:步长]

[:]提取从开头到结尾的整个字符串;

[start:]提取从start到结尾的字符串

[:end]提取从开头到end-1的字符串

[start:end]提取从start到end-1的字符串

[start:end:step]提取从start到end-1的字符串,每step个字符提取一个

>>> letters
'abcdefghijklmnopqrstuvwxyz'
>>> letters[:]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[20:]
'uvwxyz'
>>> letters[10:]
'klmnopqrstuvwxyz'
>>> letters[12:14]
'mn'
>>> letters[-3]
'x'
>>> letters[-3:]
'xyz'
>>> letters[18:-3]
'stuvw'
>>> letters[-6:-2]
'uvwx'
>>> letters[::7]
'ahov'
>>> letters[4:20:3]
'ehknqt'
>>> letters[19::4]
'tx'
>>> letters[:21:5]
'afkpu'

步长为负数

起始下标要大于终止下标

会从右往左提取,

[a:b:c]a永远表示起点,b永远表示终点,c表示步长和正序倒序,假设c为正数,a不写就默认为0;

假设c为负数,a不写就默认为最后一个元素

此时的start为从右往左的偏移量,end为从左往右的偏移量,

>>> letters
'abcdefghijklmnopqrstuvwxyz'
>>> letters[24:22:-1]
'yx'
>>> letters[:22:-1]
'zyx'
>>> letters[:24:-1]
'z'

小于起始位置的偏移量会被当成0,大于终止位置的偏移量会被当成-1。

>>> letters[-100:]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[0:]
'abcdefghijklmnopqrstuvwxyz'
>>> letters[-1:]
'z'
>>> letters[:1000]
'abcdefghijklmnopqrstuvwxyz'
>>>

len()函数:

获得字符串长度

>>> len(letters)
26
>>> empty = " "
>>> len(empty)
1
>>> empty = ""
>>> len(empty)
0
>>> a = 11111
>>> len(a)
Traceback (most recent call last):File "", line 1, in 
TypeError: object of type 'int' has no len()

split()函数:

分割字符串,基于分隔符将字符串分割成由若干子串组成的列表;

split()函数传入的参数是分隔符,传参为空时,默认的使用空白字符(换行符、空格、制表符)作为分隔符。

>>> note1 = "hello,my,first name,is,Tom"
>>> note1.split(",")
['hello', 'my', 'first name', 'is', 'Tom']
>>> note1.split()
['hello,my,first', 'name,is,Tom']

join()函数:

将含有若干子串的列表合并成一个大的字符串;调用方法分隔符.join(列表)

>>> note1 = "hello,my,first name,is,Tom"
>>> note2 = note1.split(",")
>>> note2
['hello', 'my', 'first name', 'is', 'Tom']
>>> ",".join(note2)
'hello,my,first name,is,Tom'
>>> "?".join(note2)
'hello?my?first name?is?Tom'

()函数:

判断字符串是否以指定字符或子字符串开头;

.(str,start,end)

被检测字符串.(指定字符串,被检测的字符串的开头位置(选填),被检测的字符串的结尾位置(选填));

start、end 为空是从整个字符串检测。

返回值:True、False

()函数:

判断字符串是否以指定字符或子字符串结尾;

.(str,start,end)

被检测字符串.(指定字符串,被检测的字符串的开头位置(选填),被检测的字符串的结尾位置(选填));

start、end 为空是从整个字符串检测。

返回值:True、False

>>> poem = '''All that doth flow we cannot liquid name
... Or else would fire and water be the same;
... But that is liquid which is moist and wet
... Fire that property can never get.
... Then 'tis not cold that doth the fire put out
... But 'tis the wet that makes it die, no doubt.'''
>>> poem
"All that doth flow we cannot liquid name\nOr else would fire and water be the same;\nBut that is liquid which is moist and wet\nFire that property can never get.\nThen 'tis not cold that doth the fire put out\nBut 'tis the wet that makes it die, no doubt."
>>> poem[0:13]
'All that doth'
>>> len(poem)
250
>>> poem.startswith("All")
True
>>> poem.startswith("All",10,20)
False
>>> poem.endswith("All")
False
>>> poem.endswith(".")
True
>>> poem.endswith(", no doubt.")
True
>>> poem.endswith(", no doubt.",10,15)
False
>>> poem.endswith("All",0,3)
True
>>> poem.endswith("All",0,2)
False
>>> poem.endswith("All",1,3)
False

find()函数:

检测字符串中第一次出现子字符串的位置;

.find(str,start,end)

被检测字符串.find(指定字符串,被检测的字符串的开头位置(选填),被检测的字符串的结尾位置(选填));

start、end 为空是从整个字符串检测;

返回值:出现子字符串的位置、-1。

rfind()函数:

检测字符串中最后一次出现子字符串的位置;

.rfind(str,start,end)

被检测字符串.rfind(指定字符串,被检测的字符串的开头位置(选填),被检测的字符串的结尾位置(选填));

start、end 为空是从整个字符串检测;

返回值:出现子字符串的位置、-1。

>>> poem.find("flow")
14
>>> poem.find("flow",15)
-1
>>> poem.rfind("flow",15)
-1
>>> poem.rfind("flow")
14
>>> poem.find("the")
73
>>> poem.rfind("the")
214
>>> poem.rfind("the",71,72)
-1

count():

统计字符串里某个字符或子字符串出现的次数;

.count(str,start,end)

被检测字符串.count(指定字符串,被检测的字符串的开头位置(选填),被检测的字符串的结尾位置(选填));

start、end 为空是从整个字符串检测;

返回值:指定字符串出现的次数。

>>> poem.count("the")
3
>>> poem.count("the",0,20)
0
>>> poem.count("the",0,100)
1

():

检测字符串是否由字母和数字组成;

返回值:至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False

>>> poem.isalnum()
False
>>> a = "hhhhh1111"
>>> a.isalnum()
True

strip():

移除字符串头尾指定的字符(默认为空格或换行符)或字符序列;

.strip(str)

被移除字符串.strip(指定字符串)

>>> setup = "a duck goes into a bar..."
>>> setup.strip(".")
'a duck goes into a bar'
>>> setup.strip("a")
' duck goes into a bar...'
>>> setup.strip(" ")
'a duck goes into a bar...'

():

将字符串的第一个字母变成大写,其他字母变小写;

.();

目标字符串.()

>>> setup.capitalize()
'A duck goes into a bar...'
>>> a = "AAAAA"
>>> a.capitalize()
'Aaaaa'

title():

返回"标题化"的字符串,使所有单词都是以大写开始,其余字母均为小写;

.title()

目标字符串.title()

>>> setup.title()
'A Duck Goes Into A Bar...'
>>> setup.istitle()
False
>>> b = "777 jjjj kkj"
>>> b.title()
'777 Jjjj Kkj'

upper():

将字符串中的小写字母转为大写字母;

.upper()

目标字符串.upper()

>>> setup.upper()
'A DUCK GOES INTO A BAR...'

lower():

将字符串中的大写字母转为小写字母;

.lower()

目标字符串.lower()

>>> a
'AAAAA'
>>> a.lower()
'aaaaa'

():

将字符串的大小写字母进行转换;

.()

目标字符串.()

>>> a = "ASSSaaaa"
>>> a.swapcase()
'asssAAAA'

():

进行字符串替换;

.(str1,str2,count)

目标字符串.(需要被替换的字符串,用于替换的新子串,需替换多少处)

count为空时替换所有被匹配的字符串。

>>> setup = "a duck goes into a bar..."
>>> setup.replace("duck","duck2",1)
'a duck2 goes into a bar...'
>>> setup.replace("duck","duck2",10)
'a duck2 goes into a bar...'
>>> setup.replace("a ","a bug",10)
'a bugduck goes into a bugbar...'
>>> setup.replace("a ","a bug",1)
'a bugduck goes into a bar...'
>>> setup.replace("a","a bug  ")
'a bug   duck goes into a bug   ba bug  r...'

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了