python的学习是沿着这本书提供的思路开始的,对新手实在是太友好了, 简洁的介绍了python 的核心内容,大大提高了学习效率,大写的赞!
写笔记,一方面是为了加深自己对一些python 技巧的理解和记忆,可以拿来就用;万一没记清楚,这也相当于一个快速查找手册,方便找到使用说明!
马上就要开始了,好开心!Good good study, day day up!
1 变量 1.1 变量命名驼峰命名法(Camel)
//驼峰命名法分为:小驼峰式 和 大驼峰式 // 小驼峰 示例 userName; camelCase; // 大驼峰示例 UserName; CamelCase;
下划线命名法(UnderScoreCase)
show_message(); string user_name;
下划线命名法(UnderScoreCase)及驼峰命名法(Camel)区别就是逻辑断点(单词)用的是下划线隔开,还是比较容易区分的 。python 中下划线命名法用的多一些。
1.2 变量类型及转换用type() 查看变量类型
a = ‘a’ print(type(a))
类型强制转换
a = ‘a’ print(int(a)) #字符型强制转换为int 型2 字符串 2.1 字符串相加、相乘
# 相加实现字符串拼接 what_he_does = 'play' his_instrument = 'guitar' his_name = 'Robert Johnson' artist_intro = his_name + what_he_does + his_instrument print(artist_intro) # 乘法实现字符串重复 words = 'words' * 3 print(words)
程序运行结果:
Robert Johnson play guitar wordswordswords2.2 字符串的分片与索引
在 [ ] 中使用冒号 :,冒号 的 左边代表字符串的分割从哪里开始,右边代表从哪里结束,冒号的左边或者右边可以省略,表示到字符串的第一个或最后一个位置。name[11:14] 表示从11开始,到13 结束,不包含14。
#输出 M M Mik Mike My name is2.2.1 举例1:文字小游戏-找出你朋友中的魔鬼~
word = 'friends' find_the_evil_in_your_friends = word[0] + word[2:4] + word[-3:-1] print(find_the_evil_in_your_friends) # 运行结果: fiend2.2.2 举例2:爬虫项目中文件重命名
在爬虫项目中,需要将上述链接的图片下载,并重命名保存。可采用下述代码:
url = 'http://ww1.site.cn/14d2e8ejw1xsusdcsbscb1920ueu388.jpg' file_name = url[-10:] print(file_name) # 运行结果: ueu388.jpg2.3 字符串方法 2.3.1 repalce( ) 字符串局部替代(利用切片方法)
phone_number = '1386-666-0006' hiding_number = phone_number.replace(phone_number[:9], '*' * 9) print(hiding_number) # 运行结果: *********00062.3.2 find( ) 子串的查找定位 模拟实现手机通讯录中的电话号码联想功能
search = '168' num_a = '1386-168-0006' num_b = '1681-222-0006' print(search + ' is at ' + str(num_a.find(search)) + ' to ' + str(num_a.find(search) + len(search)) + ' of num_a') print(search + ' is at ' + str(num_b.find(search)) + ' to ' + str(num_b.find(search) + len(search)) + ' of num_b') # 运行结果: # 168 is at 5 to 8 of num_a # 168 is at 0 to 3 of num_b2.3.3 format( ) 字符串格式化符号
print('{} a word she can get what she {} for.'.format('With','came')) print('{preposition} a word she can get what she {verb} for.'.format(preposition = 'with',verb = 'came')) print('{0} a word she can get what she {1} for.'.format('With','came')) city = input('write down the name of city:') url = 'http://apistore.baidu.com/microservice/weather?citypinyin={}'.format(city) print(url) # 运行结果: # With a word she can get what she came for. # with a word she can get what she came for. # With a word she can get what she came for. # write down the name of city:chengdu # http://apistore.baidu.com/microservice/weather?citypinyin=chengdu3 注释
中文注释会导致报错,需要在文件开头加一行魔法注释
#coding:utf-8