1、第一步声明编码 ,在代码的第一行写入(windows 系统)
# -*- coding: utf8 -*-
或者
第一行规则的一个例外是源代码以 UNIX“shebang”行开头。在这种情况下,应将编码声明添加为文件的第二行。例如:
#!/usr/bin/env python3
# -*- coding: utf8 -*-
2、打印特殊字符
如果您不希望前面的字符被\
解释为特殊字符,您可以通过在第一个引号前添加一个来使用原始字符串:r
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
3、多行注释
字符串文字可以跨越多行。一种方法是使用三引号: """..."""
或'''...'''
。行尾会自动包含在字符串中,但可以通过\
在行尾添加一个来防止这种情况。下面的例子:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
4、字符链接
字符串可以用运算符连接(粘在一起)+
,并用 重复*
:
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
5、字符串截取
字符串可以被索引(下标),第一个字符的索引为 0。没有单独的字符类型;一个字符只是一个大小为 1 的字符串:
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
索引也可以是负数,从右开始计算:
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
请注意,由于 -0 与 0 相同,负索引从 -1 开始。
除了索引之外,还支持切片。索引用于获取单个字符,而切片允许您获取子字符串:
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
切片索引有有用的默认值;省略的第一个索引默认为零,省略的第二个索引默认为被切片的字符串的大小。
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'
请注意如何始终包含开始,而始终排除结束。这确保始终等于:s[:i] + s[i:]``s
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
记住切片如何工作的一种方法是将索引视为 字符之间的指向,第一个字符的左边缘编号为 0。然后**n个字符的字符串的最后一个字符的右边缘具有索引n,例如:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
第一行数字给出索引 0…6 在字符串中的位置;第二行给出了相应的负指数。从i到 j的切片由分别标记为i和j的边之间的所有字符组成。
对于非负索引,切片的长度是索引的差异,如果两者都在边界内。例如,长度word[1:3]
为2。
尝试使用太大的索引会导致错误:
word[42] # the word only has 6 characters
Traceback (most recent call last):
File "", line 1, in
IndexError: string index out of range
但是,超出范围的切片索引在用于切片时会得到妥善处理:
>>> word[4:42]
'on'
>>> word[42:]
''
Python 字符串无法更改——它们是不可变的。因此,分配给字符串中的索引位置会导致错误:
>>> word[0] = 'J'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment
如果你需要一个不同的字符串,你应该创建一个新的:
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
内置函数len()
返回字符串的长度:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
6、字符串的定义及转换(str函数)
Python 中的文本数据是用str
对象或字符串处理的。字符串是 Unicode 代码是不可变 序列。字符串有多种写法:
'allows embedded "double" quotes'
"allows embedded 'single' quotes"
'''Three single
quotes’‘’``“”“Three double quotes”“”`三引号字符串可以定义多行内容。如下
'''
中国
美国
德国
法国
'''
7、关于字符串处理的各种函数介绍
# str() 把非字符串类型转换成字符串类型
a = 12345
type(a)
---------- int 整数类型
a = abcd ------------ 字符串需要使用单引号或双引号或三引号引起来,否则报错。
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.2\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
coro = func()
File "", line 1, in
NameError: name 'abcd' is not defined
a = 'abcd'
type(a)
---------- 这里的a 变量定义的是str 字符类型
str(a)
'abcd'
c = str(a)
type(c)
a.casefold()
'abcd'
a = 12345 ---------- 这里的a 变量定义的是 int 整数类型
使用str函数把非字符串类型转换成字符串类型
str(a)
# 返回首字母为大写的字符串
a = 'abcd'
>>> a.capitalize()
'Abcd'
>>> b.center(7)
' AcDBe '
>>> b.center(30)
' AcDBe '
str.encode(encoding='utf-8')
>>> b.encode(encoding='utf-8')
>>> b'AcDBe'
>>> a='小明是中国馆人'
>>> a.encode(encoding='utf-8')
>>> b'\xe5\xb0\x8f\xe6\x98\x8e\xe6\x98\xaf\xe4\xb8\xad\xe5\x9b\xbd\xe9\xa6\x86\xe4\xba\xba'
#把字节转换成字符串
>>>b = a.encode(encoding='utf-8')
>>>b.decode()
>>>'小明是中国馆人'
>>>b.decode(encoding='utf-8')
>>>'小明是中国馆人
# 判断字符串是以什么结尾
a = 'abecdf'
if a.endswith('e'):
print('该字符串是以e结尾')
else:
print('该字符串是以f结尾')
该字符串是以f结尾
a.startswith('a')
True
a.startswith('c')
False
使用空格替换字符串中的’\t’键 str.expandtabs()
a='abcdefgdddddddddddddddddddddddddddddddddddddd\tabcdedf\tabcdefgt'
a.expandtabs()
'abcdefgdddddddddddddddddddddddddddddddddddddd abcdedf abcdefgt'
a.expandtabs(1)
'abcdefgdddddddddddddddddddddddddddddddddddddd abcdedf abcdefgt'
a.expandtabs(2)
'abcdefgdddddddddddddddddddddddddddddddddddddd abcdedf abcdefgt'
a.expandtabs(3)
'abcdefgdddddddddddddddddddddddddddddddddddddd abcdedf abcdefgt'
a.expandtabs(4)
'abcdefgdddddddddddddddddddddddddddddddddddddd abcdedf abcdefgt'
a.expandtabs(5)
'abcdefgdddddddddddddddddddddddddddddddddddddd abcdedf abcdefgt'
a.expandtabs(6)
'abcdefgdddddddddddddddddddddddddddddddddddddd abcdedf abcdefgt'
a.expandtabs(7)
'abcdefgdddddddddddddddddddddddddddddddddddddd abcdedf abcdefgt'
返回在切片 s[start:end] 中找到子字符串 sub 的字符串中的最低索引。可选参数 start 和 end 被解释为切片符号。如果未找到 sub,则返回 -1。
a ='abcdedfgabchhhhhabckkkk'
a ='abcdedfgabchhhhhabckkkk'
a.find(b)
0 -------------> 第一个符合条件的所以位,索引从0开始
a.find(b,0,-1)
0
a.find('abc',0,-1)
0
a.find('abc')
0
a ='acdedfgabchhhhhabckkkk'
a.find('abc')
7
# 第一种 旧方法
%s ----> 字符串
%d ----> 数字
前后必须一一对应,不能多也不能少。
>>> '小明,你是 %s 人吗?' %('上海')
'小明,你是 上海 人吗?'
>>> '小明,你是 %s 人吗?' %('北京')
'小明,你是 北京 人吗?'
'小明,你是 %s 人吗?' %('美国')
'小明,你是 美国 人吗?'
'%s 是 %s 人, 来自 %s。'% ('韩梅梅','美国','中国北京')
'韩梅梅 是 美国 人, 来自 中国北京。'
'%s 是 %s 人, 来自 %s。'% ('欧巴一','巴西','韩国釜山')
'欧巴一 是 巴西 人, 来自 韩国釜山。'
'%s 是 %s 人, 今年 %d 岁了。'% ('拜登','巴西',88)
'拜登 是 巴西 人, 今年 88 岁了。'
'%s 是 %s 人, 今年 %d 岁了。'% ('特朗普','中国人',188)
'特朗普 是 中国人 人, 今年 188 岁了。'
'%s 是 %s 人, 今年 %d 岁了。'% ('特朗普','中国人',188,'奥巴马')
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.2\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
coro = func()
File "", line 1, in
TypeError: not all arguments converted during string formatting
'%s 是 %s 人, 今年 %d 岁了。'% ('特朗普','中国人')
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.2\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
coro = func()
File "", line 1, in
TypeError: not enough arguments for format string
使用参数导入
name='普京'
guojia='俄罗斯'
age='70' ------------> 数字加上引号后就变成了字符类型
'%s 是 %s 人, 今年 %d 岁了。'% (name,guojia,age)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.2\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
coro = func()
File "", line 1, in
TypeError: %d format: a number is required, not str
age=70
'%s 是 %s 人, 今年 %d 岁了。'% (name,guojia,age)
'普京 是 俄罗斯 人, 今年 70 岁了。'
第二种 新方法(str.format())
'{} 是 {} 人, 今年 {} 岁了。'.format(name,guojia,age)
'普京 是 俄罗斯 人, 今年 70 岁了。'
格式化浮点数 "10.2f" 10 -->指定数值的宽度,数值长度不足时使用空格填充,2指定小数点后的数值长度。
print(format(57.467657,“10.2f”)) -----> 57.47
print(format(12345678.923,“10.2f”)) -----> 12345678.92
print(format(57.4,“10.2f”)) ----> 57.40
print(format(57,“10.2f”)) ------> 57.00
格式化成百分数
可以使用转换码‘%’ 将一个数值格式化百分数。例如:
print(format(0.53457,"10.2%"))
" 53.46%"
print(format(0.00033923,"10.2%"))
" 0.34"
print(format(7.4,"10.2%"))
" 740.00%"
print(format(57,"10.2%"))
"005700.00%"
调整格式默认是右对齐,如果需要做对齐,可以使用符号"<" 放在格式说明符里指定得到的字符串是已制定的宽度向左对齐的。
print(format(57.467657,"10.2f"))
print(format(57.467657,"<10.2f"))
print(format(76.123456,"<14.2f"))
"76.12 "
print(format(76.123456,"14.2f"))
" 76.12"
**格式化字符串**
print(format('welcome to python',"20s"))
welcome to python
print(format('welcome to python',"30s"))
welcome to python
print(format('welcome to python',"<30s"))
welcome to python
print(format('welcome to python',">30s"))
" welcome to python"
print(format('welcome to python and java.','>20s'))
welcome to python and java.
print(format('welcome to python and java.','>10s')) ---------> 指定的字符宽度小于字符的宽度时,默认打印所有字符。
welcome to python and java.
print(format('welcome to python and java.','>50s'))
" welcome to python and java." 注意: 引号默认没有,这里加上是为了方便识别。
第三种 'f'
name='普京'
guojia='俄罗斯'
age=70
f'{name} 是 {guojia} 人, 今年 {age}岁了。'
'普京 是 俄罗斯 人, 今年 70岁了。'
f'{name} 是 {guojia} 人, 今年 {age}岁了。'
'普京 是 俄罗斯 人, 今年 70岁了。'
f'{name} 是 {guojia} 人, 今年 {age}岁了。'
'普京 是 俄罗斯 人, 今年 70岁了。'
age='80' ----------> 对变量的类型没有要求
f'{name} 是 {guojia} 人, 今年 {age}岁了。'
'普京 是 俄罗斯 人, 今年 80岁了。'
第四种 使用Template string 标准库
>>> from string import Template
>>> t = Template('Hey, $name!')
>>> t.substitute(name=name)
'Hey, Bob!'
Conversion | Meaning | Notes |
'd' |
Signed integer decimal. 有符号的十进制数据 | |
'i' |
Signed integer decimal. 有符号的十进制数据 | |
'o' |
Signed octal value. 有符号的八进制 | (1) |
'u' |
Obsolete type – it is identical to 'd' . 与d相同 现在以不再使用 |
(6) |
'x' |
Signed hexadecimal (lowercase). 十六进制 (小写) | (2) |
'X' |
Signed hexadecimal (uppercase). 十六进制(大写) | (2) |
'e' |
Floating point exponential format (lowercase). (科学计数法 小写e) | (3) |
'E' |
Floating point exponential format (uppercase). (科学计数法大写E) | (3) |
'f' |
Floating point decimal format. 浮点数 | (3) |
'F' |
Floating point decimal format. 浮点数 | (3) |
'g' |
Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. | (4) |
'G' |
Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. | (4) |
'c' |
Single character (accepts integer or single character string). 只接受 单个字符或数字 | |
'r' |
String (converts any Python object using repr() ). |
(5) |
's' |
String (converts any Python object using str() ). 任意字符串 |
(5) |
'a' |
String (converts any Python object using ascii() ). 把字符串串转换成ascii 进行显示 |
(5) |
'%' |
No argument is converted, results in a '%' character in the result. 打印百分号是可以使用‘%%’ |
>>>number=1.2
>>>'this is a number: %d'% (number)
'this is a number: 1'
>>> 'this is a number: %f'% (number)
'this is a number: 1.200000'
>>> 'this is a number: %e'% (number)
'this is a number: 1.200000e+00'
>>> 'this is a number: %E'% (number)
'this is a number: 1.200000E+00'
>>> 'this is a number: %f(2)'% (number)
'this is a number: 1.200000(2)'
>>>'this is a number: %F'% (number)
'this is a number: 1.200000'
>>>'this is a number: %g'% (number)
'this is a number: 1.2'
>>>number = 1.23456
>>>'this is a number: %g'% (number)
'this is a number: 1.23456'
>>>'this is a number: %G'% (number)
'this is a number: 1.23456'
>>>number = 1.234564566666666666
>>> 'this is a number: %G'% (number)
'this is a number: 1.23456'
>>>'this is a number: %g'% (number)
'this is a number: 1.23456'
>>>number = 122222222222.234564566666666666
>>>'this is a number: %g'% (number)
'this is a number: 1.22222e+11'
>>>number = 123456.12345
>>>'this is a number: %g'% (number)
'this is a number: 123456'
>>>'this is a number: %G'% (number)
'this is a number: 123456'
>>>number = 122222222222.234564566666666666
>>>'this is a number: %f'% (number)
'this is a number: 122222222222.234558'
>>>'this is a number: %F'% (number)
'this is a number: 122222222222.234558'
>>>'this is a number: %E'% (number)
'this is a number: 1.222222E+11'
number='11222.23222'
'this is a number: %s'% (number)
'this is a number: 11222.23222'
'this is a number: %c'% (number)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.2\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
coro = func()
File "", line 1, in
TypeError: %c requires int or char
>>> a='a'
>>> b='ab'
>>> 'this is a number: %c'% (a)
'this is a number: a'
>>>a='1'
>>> 'this is a number: %c'% (a)
'this is a number: 1'
'this is a number: %a'% (b)
"this is a number: 'ab'"
>>>a='物品'
>>>'this is a number: %a'% (a)
"this is a number: '\\u7269\\u54c1'"
>>>a=76.7
>>>'this is a number: %d%%'% (a)
'this is a number: 76%'
>>>'this is a number: %g%%'% (a)
'this is a number: 76.7%'
Flag && Meaning
'#'
The value conversion will use the “alternate form” (where defined below).
'0'使用0填充达到指定的长度: %010d 如果数字小于10位会在数字的前面添加0补到10位。不指定0就使用空格补充。
>>>a=12
>>>print('this is a word:%03d'% (a))
this is a word:012
>>>print('this is a word:%06d'% (a))
this is a word:000012
>>>print('this is a word:%6d'% (a))
this is a word: 12
The conversion will be zero padded for numeric values.
'-' 就是从字符串的后面补充空格来达到你指定的输出长度,看不出来但是确实存在。
this is a word: this is a number
The converted value is left adjusted (overrides the '0'
conversion if both are given).
' '
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
'+' 就是从字符串的前面补充空格来达到你指定的输出长度
print('this is a word: %+40s'% (a))
this is a word: this is a number
A sign character ('+'
or '-'
) will precede the conversion (overrides a “space” flag).
print('this is a word: %-20s'% (a))
this is a word: this is a number
print('this is a word: %-100s'% (a))
this is a word: this is a number
print('this is a word: %+100s'% (a))
this is a word: this is a number
print('this is a word: %+10s'% (a))
this is a word: this is a number
print('this is a word: %+20s'% (a))
this is a word: this is a number
print('this is a word: %+40s'% (a))
this is a word: this is a number
print('this is a word: %-40s'% (a))
this is a word: this is a number
print('this is a word: % s'% (a))
this is a word: this is a number
print('this is a word:% s'% (a))
this is a word: this is a number
print('this is a word:%s'% (a))
this is a word: this is a number
print('this is a word:%' 's'% (a))
this is a word: this is a number
print('this is a word:% s'% (a))
this is a word: this is a number
a=12
print('this is a word:%03d'% (a))
this is a word:012
print('this is a word:%06d'% (a))
this is a word:000012
print('this is a word:%6d'% (a))
this is a word: 12
print('this is a word:%#d'% (a))
this is a word:12
print('this is a word:%####d'% (a))
this is a word:12
a = '我是中国人'
a.index('中')
2
a.index('爱')
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.2\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
coro = func()
File "", line 1, in
ValueError: substring not found
a.find('爱')
-1
a='123'
a.isalnum()
True
b='acb'
b.isalnum()
True
c='ac123'
d=123
d.isalnum()
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2022.3.2\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
coro = func()
File "", line 1, in
AttributeError: 'int' object has no attribute 'isalnum'
c.isalnum()
True
'%^^***('.isalnum()
False
'a%^^***('.isalnum()
False
''.isalnum()
False
'ab&c1'.isalnum()
False
'c1'.isalnum()
True
>>> a='abc'
>>> b='ABC'
>>> c='ab12'
>>> a.isalpha()
True
>>> b.isalpha()
True
>>> c.isalpha()
False
>>> d='2#'
>>> d.isalpha()
False
>>> e=''
>>> e.isalpha()
False
>>> a='1'
>>> b=123
>>> c=12.3
>>> d='123d'
a.isdecimal()
True
>>> b='12.3'
>>> b.isdecimal()
False
>>> d.isdecimal()
False
>>> w='五'
>>> w.isdecimal()
False
>>> a='1'
>>> b=123
>>> c=12.3
>>> d='123d'
>>> w='五'
>>> w.isdecimal()
False
>>> w.isdigit()
False
>>> w.isnumeric()
True
>>> a.isnumeric()
True
>>> b.isnumeric()
False
>>> w.isnumeric()
True
>>> a='abcd'
>>> b='AbcD'
>>> a.islower()
True
>>> b.islower()
False
>>> c='A%C'
>>> c.islower()
False
a.count('a')
1
a='aaaaa'
a.count('a')
5
a=''
a='ac '
b='a b c d'
a.isspace()
False
c='ac '
b.isspace()
False
c.isspace()
False
e=' '
e.isspace()
True
f='\t'
f.isspace()
True
a='abcd'
b='acdeE'
c='ABAC'
a.isupper()
False
b.isupper()
False
c.isupper()
True
>>> a=('a','b','c','e')
>>> symbol = "-"
>>> symbol.join(a)
'a-b-c-e'
a='abcdef'
a.ljust(2)
'abcdef'
a.ljust(10)
'abcdef '
a.ljust(20)
'abcdef '
a.rjust(2)
'abcdef'
a.rjust(20)
' abcdef'
>>> a='acbde'
>>> d='ACED'
>>> a.upper()
'ACBDE'
>>> d.lower()
'aced'
注意注意注意
a= ‘abccba’
a.rstrip(‘abc’) --------------> 分别删除以a 或b或c开通的字符,最后返回空字符’’
‘Arthur: three!’.removeprefix('Arthur: ')
'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
str.removesuffix(suffix, /)
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]
. Otherwise, return a copy of the original string:
>>>
>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'
New in version 3.9.
>>> a=' abcd eftg '
>>> a.strip()
'abcd eftg'
>>> a.lstrip()
'abcd eftg '
>>> a.rstrip()
' abcd eftg'
删除指定字符
>>> a='abccba'
>>> a.strip('ab')
'cc'
>>> a.lstrip('ab')
'ccba'
>>> a.lstrip('ba')
'ccba'
>>> a.rstrip('ba')
'abcc'
>>> a.rstrip('abc')
''
>>>'www.example.com'.lstrip('cmowz.')
'example.com'
>>>'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>>'Arthur: three!'.removeprefix('Arthur: ')
'three!'
**注:**两个字符串的长度必须相同,为一一对应的关系。
以下实例展示了使用 maketrans() 方法将所有元音字母转换为指定的数字:
实例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from string import maketrans # 必须调用 maketrans 函数。
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
以上实例输出结果如下:
th3s 3s str3ng 2x1mpl2....w4w!!!
str.split(sep=None, maxsplit=- 1)
a='www.baidu.com'
a.partition('.')
('www', '.', 'baidu.com')----> 第一个元素为第一行 第二个元素为分隔符 第三个为第二列
a='www.baidu.com'
a.split('.')
['www', 'baidu', 'com']
a='''
... a
... b
... c
... d
... e
... f
... g
... '''
>>> a.splitlines()
['', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
>>>
>>> a='ABcdEG'
>>> a.swapcase()
'abCDeg'
>>>
>>> a.zfill(10)
'0000ABcdEG'
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
>>> b='abc123efe12abcde1212'
>>> b.replace('12','AB')
'abcAB3efeABabcdeABAB'
>>> b.replace('12','AB',1)
'abcAB3efe12abcde1212'
>>> b.replace('12','AB',2)
'abcAB3efeABabcde1212'
>>> b.replace('12','AB',4)
'abcAB3efeABabcdeABAB'
>>> print(b) ----------------> 字符串不能修改,只是复制一份在进行修改。
abc123efe12abcde1212
>>> b.replace('12','AB')
'abcAB3efeABabcdeABAB'
>>> a='hello world'
>>> a.title()
'Hello World'
import keyword
keyword.iskeyword('def')
True
keyword.iskeyword('abc')
False
keyword.iskeyword('hello')
False
keyword.iskeyword('import')
True
keyword.iskeyword('python')
False
keyword.iskeyword('class')
True
查看所有的关键字,关键字有特殊意义。
a=keyword.kwlist
keyword.kwlist
['False', 'None', 'True', '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']