Python基础核心概念
1 变量和简单数据类型
变量命名格式:变量名 = “赋值”
1.1 变量使用规范
使用变量时,需要遵守一些规则。违反这些规则将引发错误。
~变量名只能包含数字、字母、下划线。变量名不能以数字开头以及不能包含空格。
~变量名不能将Python保留字和函数名作为变量名。如print等
如下是python3的33个保留字列表:
~变量名要简单又具有描述性。如name比n好,user_name比u_n好。
~慎用大写字母I和O,避免看错成数字1和0。
1.2 字符串
字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中引号包括单引号和双引号。这种灵活性能够在字符串中包含引号和撇号,如:
>>> str = "I'm David">>> str1 = 'I told my friend,"i love Python"'
常用字符串操作方法
以首字母大写的方式显示每个单词:
>>> name = "hello python world" >>> print(name.title())
将字符串改为全部大写或全部小写:
>>> str1 = "I love python">>> print(str1.upper()) #将字符串改为全部大写I LOVE PYTHON >>> print(str1.lower()) #将字符串改为全部小写i love python
字符串合拼(拼接)
Python使用加号(+)来合拼字符串,如:\
>>> first_name = "Guido">>> last_name = "van Rossum">>> full_name = first_name + " " + last_name >>> print(full_name)Guido van Rossum
使用制表符\t或换行符\n添加空白:
>> print("Languages:\\n\\tPython\\n\\tC++\\n\\tPHP")Languages: Python C++ PHP
删除字符串的空格:
>>> name = " p y t h o n ">>> print(name.rstrip()) #删除字符串右端空格 p y t h o n >>> print(name.lstrip()) #删除字符串左端空格p y t h o n >>> print(name.strip()) #删除字符串两端空格p y t h o n >>> print(name.replace(' ','')) #删除字符串全部空格包括制表符和换行符python
字符串的序号
字符串是字符的序列,可以按照单个字符或字符片段进行索引。
>>> name = "Hello World">>> print(name[0])H >>> print(name[0:-1])Hello Worl >>> print(name[-1])d >>> print(name[::])Hello World >>> print(name[0:11])Hello World
找到字符串中最低字符索引号:S.find(sub [,start [,end]]) -> int
失败时返回-1
>>> name = "hello world">>> print(name.find('d')) 10
返回某些字符出现的次数:S.count(sub[, start[, end]]) -> int
>>> name = "hello world">>> print(name.count('l')) 3
把字符串由分隔符返回一个列表:S.split([sep [,maxsplit]]) -> list of strings,如果给定maxsplit,则最多为maxsplit
>>> name = "hello world">>> print(name.split(' '))['hello', 'world'] >>> print(name.split(' ',0)) ['hello world']
字符串格式化输出(format和%用法)
%方法格式代码
\
>>> "{}:计算机{}的CPU占用率为{}%".format('2019-03-25','python',10) #S.format(\*args, \*\*kwargs) -> string'2019-03-25:计算机python的CPU占用率为10%' >>> "%s:计算机%s的CPU占用率为%d%%" % ('2019-03-25','python',10) #%用法 '2019-03-25:计算机python的CPU占用率为10%
小结:可以用help函数查看字符串的相关操作,比如help(str.find)