变量,基本数据类型,字符串

一、 变量的声明

python语言是动态语言

变量不需要事先声明
变量的类型不需要声明
每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。

在 Python 中,变量就是变量,它没有类型,我们所说的类型,是变量在内存中所指的对象的类型

二、 变量命名规则:

可以包含以下字符:
1)大小写字母(a-z,A-Z)
2)变量名区分大小写; a 和 A 是不同的变量
3)数字(0-9)
4)下划线(_)

==不可以以数字开头==
不要以单下划线和双下划线开头;如:_user或 __user
变量命名要易读;如:user_name,而不是username
不用使用标准库中(内置)的模块名或者第三方的模块名
不要用这些 Python 内置的关键字:
['False', 'None', 'True', 'and', 'as', 'assert', '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']

基本数据类型

1.整形:任何仅含数字的序列在 Python 中都被认为是整型
2.浮点型:带小数点的数字
3.字符串类型
4.布尔类型

强制类型转换

1)>>> int(0.1)
0

int(0.9)
0

2)int 不能对字符串类型表示的浮点数进行转换:
In [52]: int('123.9')


ValueError Traceback (most recent call last)
<ipython-input-52-843b2aecee10> in <module>()
----> 1 int('123.9')
ValueError: invalid literal for int() with base 10: '123.9'

3)>>> float(1)
1.0

4)把其他类型转换为字符串

str(1)
'1'
str(1.0)
'1.0'
str(True)
'True'
str(False)
'False'

5)把其他类型转换为布尔型

image.png

字符串

简单操作
\ 转义符
testimony = 'This shirt doesn't fit me' 转义符号 ‘

words = 'hello \nworld' 换行

+拼接
print('hello' + 'world')

不可以用 字符串和 一个非字符串类型的对象相加
'number' + 0 # 这是错误的

  • 复制
    print('*' * 20)
    print('shark' * 20)

字符串 和 0 或者 负数相乘,会得到一个空字符串
In [76]: 'hey' * 0
Out[76]: ''

In [77]: 'hey' * -3
Out[77]: ''

偏移量

image.png

image.png

s[0:2:2] 步长为2,从左往右取数
s[0:2:-2] 从右往左取数

利用字符串对象的方法

split (类似于shell中的awk)

url = 'www.qfedu.com 千锋官网'
url.split()

li = url.split('.')

host, *_ = url.split('.', 1)[0]   取出来是一个列表,在取出第一个位置

rsplit 从右向左分割

url = 'www.qfedu.com'
url2 = url.rsplit('.', 1)

replace 替换

url = 'www.qfedu.com'
url2 = url.replace('.', '_')

strip 移除两端的空格

s = ' hello   '
s2 = s.strip()

inp = input(">:").strip()     链式表达式

s = "symbol=BCHBTC;baseCoin=BCH;quoteCoin=BTC;"

s_list = s.split(';')
# print(s_list)
# ['symbol=BCHBTC', 'baseCoin=BCH', 'quoteCoin=BTC', '']

startswith 判断字符串以什么为开头
s = 'hello world'
if s.startswith('h'):
print(s)

endswith 判断字符串以什么为结尾
s = 'hello world'
if s.endswith('d'):
print(s)

index 获取一个元素在字符串中的索引号
s = 'hello world'
idx = s.index('l')

image.png

image.png
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容