当前位置: 移动技术网 > IT编程>脚本编程>Python > 关于python的语法学习讲解

关于python的语法学习讲解

2018年03月20日  | 移动技术网IT编程  | 我要评论

帝王修魔录,www.mail.ru,小黑mm小游戏

1、Python中语句结束不需要以分号结束,变量不需要提前定义。

2、

a = 'word'

print(a*3) #字符串乘法

#result wordwordword

字符串乘以一个数字,意思就是将字符串复制这个数字的份数。

3、

a = 'I love python'

print(a[0]) #取字符串第一个元素

#result I

print(a[0:5]) #取字符串第一个到第五个元素

#result I lov

print(a[-1]) #取字符串最后一个元素

#result n

通过下图就能清楚的理解字符串的切片和索引:

4、字符串方法

1)split()方法

a = 'www.baidu.com'

print(a.split('.'))

# result ['www', 'baidu', 'com']

2)repalce()方法

a = 'There is apples'

b = a.replace('is','are')

print(b)

# result There are apples

3)strip()方法

a = ' python is cool '

print(a.strip())

# result python is cool

strip()方法返回去除两侧(不包括内部)空格的字符串,也可以指定需要去除的字符,将他们列为参数中即可。

a = 'python is cool'

print(a.strip('l'))

# result python is coo

4)format()方法

字符串格式化,基本语法是通过 {} 和 : 来代替以前的 % 。

print("{:.2f}".format(3.1415926)) #3.14

a = '{} is my love'.format('Python')

print(a)

# result Python is my love"{1} {0} {1}".format("hello", "world") # 设置指定位置

# 'world hello world'

print("网站名:{name}, 地址 {url}".format(name="动图菜菜", url="www.halicaicai.cn"))

# 通过字典设置参数

site = {"name": "动图菜菜", "url": "www.halicaicai.cn"}

print("网站名:{name}, 地址 {url}".format(**site))

# 通过列表索引设置参数

my_list = ['动图菜菜', 'www.halicaicai.cn']

print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

5、Python中定义函数的方法

def 函数名 (参数1,参数2...):

return '结果'

6、Python的判断语句格式if condition:

do

else:

do

# 注意:冒号和缩进不要忘记了

# 再看一下多重条件的格式

if condition:

do

elif condition:

do

else:

do

7、Python的循环语句

#for循环

for item in iterable:

do

#item表示元素,iterable是集合

for i in range(1,11):

print(i)

#其结果为依次输出1到10,切记11是不输出的,range为Python内置函数。

#while循环

while condition:

do

8、元组的元素不能够修改,只能查看,元组的格式如下。

tuple = (1,2,3)

集合中的元素是无序的,不可重复的对象,有时,可以通过集合把重复的数据去除掉。

list = ['xiaoming','zhangyun','xiaoming']

set = set(list)

print(set)

# result {'zhangyun', 'xiaoming'}

9、文件操作

Python中通过open()函数打开文件,语法如下:

open(name[, mode[, buffering]])

open()函数使用文件名做为唯一的强制参数,然后返回一个文件对象。模式(mode)和缓冲(buffering)是可选参数。在Python的文件操作中,mode参数的输入是有必要的,而buffering使用较少。

f = open('C:/Users/Administrator/Desktop/file.txt','r+')

#f.write('hello world')

print ("文件名为: ", f.name)

content = f.read()

print('内容:',content)

通过f.write()方法和f.read()方法写入和读取数据。

使用close()方法关闭文件。

f.close()

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网