Loading... # 第1章 变量和简单数据类型 ## 1.1 变量的使用和命名 ```python message = "Hello World" print(message) ``` <b>运行结果:</b> > Hello World <b>变量命名规则:</b> - 变量名只能包含**字母、数字、下划线** - 变量名可以字母或者下划线打头,**但不能以数字打头** - 不能将Python关键字当做变量名 1.2 字符串 ---------- <b>字符串</b> 就是一新系列字符。在Python中,用引号括起来的都是字符串。其中引号可以是**单引号**,也可是**双引号**,**这使得你能够在字符串中包含引号和撇号**。 例如: ```python "This's a string" 'This is also a string' 'I told you, "Python is the best in the world!" ' "It's beautiful." ``` 1.2.1 使用方法修改字符串的大小写 -------------------------------- ```python name = "ada lovelace" print(name.title()) name = "ADa" print(name.title()) print(name.upper()) print(name.lower()) ``` 输出结果: > Ada Lovelace > Ada > ADA > ada > !!! > <font size = 4><b>方法</b> 是Python可对数据进行的操作。</font> > !!! - 方法`title()`以首字母大写的方式显示每个单词。 - 方法`upper()`以大写显示所有字母字符 - 方法`lower()`以小写显示所有字符字母 ### 1.2.2 合并(拼接)字符串 ```python first_name = "ada" second_name = "lovelace" full_name = first_name + " " + second_name print(full_name) print(full_name*3) ``` 输出结果: > ada lovelace > ada lovelaceada lovelaceada lovelace > !!! > Python用 <b>加号 (+)和乘号 (*)</b> 来合并字符串。这种合并方法称为 <u>拼接</u> 。 <br></br> !!! *e.g:* ```python #接上代码 message = "Hello, " + full_name.title() + "!" print(message) ``` 输出结果: > Hello, Ada Lovelace! ### 1.2.3 删除空白 ```python s = " python " print(s.lstrip()) print(s.rstrip()) print(s.strip()) print(s) ``` 输出结果: > python· (·代表空格) > ·python > python > ·python· <br> !!! <u>空白</u> 泛指任何非打印字符,包括空格、制表符和换行符。 !!! - 方法`strip()`删除字符串首尾空格。 - 方法`lstrip()`删除字符串首空格。 - 方法`rstrip()`删除字符串尾空格。 - 可以发现,在使用过这些方法后,原字符串并没有发生相应的变化 !!! <br></br> !!! ## 1.3 数字 ### 1.3.1 整数 Python使用两个乘号表示乘法运算 ```python >>> 3 ** 2 9 >>> 3 ** 3 27 ``` ### 1.3.2 浮点数 ### 1.3.3 函数str() 在字符串中需要用到数字变量的值时 ```python age = 25 print("Happy " + age + "th Birthday") #这种写法是错误的 ------------------------------------------------------------ 返回错误报告: Traceback (most recent call last): File "D:/Pytest/1.py", line 2, in <module> print("Happy " + age + "th Birthday") TypeError: can only concatenate str (not "int") to str ``` !!! 之所以会出现这样的错误,是因为<u>类型不匹配</u><br> Python无法将 int 和 str 类型的变量拼接在一起 !!! 为此可以调用`str()`函数,将非字符串变量表示为字符串 ```python age = 25 print("Happy " + str(age) + "th Brithday") ``` 输出结果为: > Happy 25th Birthday 最后修改:2021 年 08 月 01 日 02 : 59 PM © 允许规范转载