Python笔记--002 变量和简单数据类型
2.1 变量的命名和使用
- 变量名只能包含字母、数字、下划线。变量名可以字母或下划线打头,如:
message_1,但不能以数字打头,不能以数字开头; - 变量名不能包含空格;
- 变量名不能包含Python关键字和函数名;
- 变量名应既简短又具有描述性,可读性,见名知意;
- 变量名最好不要用小写字母
i和大写字母O;
2.2 字符串
2.2.1 使用方法修改字符串的大小写
函数titlle()
title()函数以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写。
name = "ada lovelace"
print(name.title())
print(name)
输出:
Ada Lovelace
ada lovelace
2.2.2 将全部的字符串改为大写或小写
函数upper() --全部大写
函数lower() --全部小写
name = "ada lovelace"
print(name.upper())
print(name.lower())
输出:
ADA LOVELACE
ada lovelace
2.2.3 合并(拼接)字符串
Python 通过
+来合并字符串。
first_name = 'ada'
last_name = 'lovelace'
full_name = first_name + ' ' + last_name
print(full_name)
输出:
ada lovelace
2.3.4 删除空白
rstrip()去除字符串末尾的空白
favorite_language = 'Python '
print(favorite_language.rstrip())
lstrip()** 去除字符串开头的空白**
strip()** 剔除字符串两端的空白**
2.4 数字
Python 中数字可以直接进行`+,-,*,/运算。
2.4.1 整数
>>> 2+3
5
>>> 5-4
1
>>> 3*6
18
>>> 6/2
3.0
幂的运算,乘方运算
>>> 2**3
8
>>> 5**5
3125
>>> 2**4
16
>>> 2**8
256
2.4.2 浮点数
>>> 0.1+0.4
0.5
>>> 3*0.6
1.7999999999999998
2.4.3 str() 函数
数字和字符串是不能直接连接的,需要将其转化为字符串
age = 23
message = "Happy " + age + "rd Birthday!"
print(message)
系统会报错:
Traceback (most recent call last):
File "/Users/liweixin/PycharmProjects/pythonProject/strings_str/str001.py", line 17, in <module>
message = "Happy " + age + "rd Birthday!"
TypeError: can only concatenate str (not "int") to str
正确的写法:
message = "Happy " + str(age) + "rd Birthday!"
2.5 注释
Python中的注释用#
2.6 Python之禅
输入import this
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

浙公网安备 33010602011771号