美文网首页
Python基础(二)

Python基础(二)

作者: Mr丶sorrow | 来源:发表于2017-10-21 23:40 被阅读0次

判断语句

if-else

if 条件:
    满足条件时要做的事情1
    满足条件时要做的事情2
    满足条件时要做的事情3
    ...(省略)...
else:
    不满足条件时要做的事情1
    不满足条件时要做的事情2
    不满足条件时要做的事情3
    ...(省略)...

elif

if xxx1:
    事情1
elif xxx2:
    事情2
elif xxx3:
    事情3

注:elif可以和else搭配一起使用。

if xxx1:
    事情1
elif xxx2:
    事情2
else:
    事情3

if嵌套

if 条件1:

    满足条件1 做的事情1
    满足条件1 做的事情2
    ...(省略)...

    if 条件2:
        满足条件2 做的事情1
        满足条件2 做的事情2
        ...(省略)...

注:

  • 外层的if判断,也可以是if-else
  • 内层的if判断,也可以是if-else
  • 根据实际开发的情况,进行选择

示例:

chePiao = 1     # 用1代表有车票,0代表没有车票
daoLenght = 9     # 刀子的长度,单位为cm

if chePiao == 1:
    print("有车票,可以进站")
    if daoLenght < 10:
        print("通过安检")
    else:
        print("没有通过安检")
else:
    print("没有车票,不能进站")

循环语句

while循环

while 条件:
    条件满足时,做的事情1
    条件满足时,做的事情2
    条件满足时,做的事情3
    ...(省略)...

示例:

i = 0
while i<5:
    print("当前是第%d次执行循环"%(i+1))
    print("i=%d"%i)
    i+=1

while循环嵌套

while 条件1:

    条件1满足时,做的事情1
    条件1满足时,做的事情2
    条件1满足时,做的事情3
    ...(省略)...

    while 条件2:
        条件2满足时,做的事情1
        条件2满足时,做的事情2
        条件2满足时,做的事情3
        ...(省略)...

示例:打印如下图形

*
* *
* * *
* * * *
* * * * *

代码:

i = 1
while i<=5:

    j = 1
    while j<=i:
        print("* ",end='')
        j+=1

    print("\n")
    i+=1

for循环

for 临时变量 in 列表或者字符串等:
    循环满足条件时执行的代码
else:
    循环不满足条件时执行的代码

示例:

name = 'hello'

for x in name:
    print(x)

break和continue

  • break的作用:用来结束整个循环
  • continue的作用:用来结束本次循环,紧接着执行下一次的循环
  • break/continue只能用在循环中,除此以外不能单独使用
  • break/continue在嵌套循环中,只对最近的一层循环起作用

字符串

python中字符串的格式

如下定义的变量a,存储的是字符串类型的值.

a = "hello"
或者
a = 'hello'

注:Python字符串双引号或者单引号皆可

字符串输出

a = 'hello'
print a

字符串输入

  • Python2:raw_input()、input()
  • Python3:input()

字符串的下标

字符串实际上就是字符的数组,如果有字符串:name = 'abcdef',在内存中的实际存储如下:

如果想取出部分字符,那么可以通过下标的方法(注意python中下标从0开始):

name = 'abcdef'

print(name[0])
print(name[1])
print(name[2])

字符串的切片

切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作。
切片的语法:[起始:结束:步长],选取的区间属于左闭右开型,即从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身)。

示例1:

name = 'abcdef'

print(name[0:3]) # 取 下标0~2 的字符
print(name[0:5]) # 取 下标为0~4 的字符
print(name[3:5]) # 取 下标为3、4 的字符
print(name[2:])  # 取 下标为2开始到最后的字符
print(name[1:-1]) # 取 下标为1开始 到倒数第2个之间 的字符

示例2:

 >>> a = "abcdef"
 >>> a[:3]
 'abc'
 >>> a[::2]
 'ace'
 >>> a[5:1:2] 
 ''
 >>> a[1:5:2]
 'bd'
 >>> a[::-2]
 'fdb' 
 >>> a[5:1:-2]
 'fd'

字符串常见操作

定义字符串mystr = 'hello world python2 and python3',以下是常见的操作。

find

检测str是否包含在mystr中,如果是返回开始的索引值,否则返回-1。

mystr.find(str, start=0, end=len(mystr))

示例:

>>> mystr = 'hello world python2 and python3'
>>> mystr.find("world")
6
>>> mystr.find("world", 0, 7)
-1

index

跟find()方法一样,只不过如果str不在 mystr中会报一个异常

mystr.index(str, start=0, end=len(mystr)) 

示例:

>>> mystr = 'hello world python2 and python3'
>>> mystr.index("world", 0, 7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

count

返回 str在start和end之间 在 mystr里面出现的次数
跟find()方法一样,只不过如果str不在 mystr中会报一个异常

mystr.count(str, start=0, end=len(mystr))

示例:

>>> mystr = 'hello world python2 and python3'
>>> mystr.count("python")
2

replace

把mystr中的str1替换成str2,如果count指定,则替换不超过count次。执行replace后,mystr不变

mystr.replace(str1, str2,  mystr.count(str1))

示例:

>>> mystr = 'hello world python2 and python3'
>>> mystr.replace("python", "PYTHON",  mystr.count("python"))
'hello world PYTHON2 and PYTHON3'
>>> mystr.replace("PYTHON", "python", 1)
'hello world python2 and python3'
>>> mystr.replace("python", "PYTHON", 1)
'hello world PYTHON2 and python3'

split

以str为分隔符切片mystr,如果maxsplit有指定值,则仅分隔maxsplit 个以str为分隔子字符串,也就是maxsplit+1个字符串。

mystr.split(str=" ", maxsplit)    

示例:

>>> mystr = 'hello world python2 and python3'
>>> mystr.split(" ")
['hello', 'world', 'python2', 'and', 'python3']
>>> mystr.split(" ", 2)
['hello', 'world', 'python2 and python3']

capitalize

把字符串的第一个字符大写

>>> mystr = 'hello world python2 and python3'
>>> mystr.capitalize()
'Hello world python2 and python3'

title
把字符串的每个单词首字母大写

>>> a = "hello"
>>> a.title()
'Hello'

startswith

检查字符串是否是以obj开头, 是则返回True,否则返回False。

mystr.startswith(obj)

示例:

>>> mystr = 'hello world python2 and python3'
>>> mystr.startswith("hello")
True
>>> mystr.startswith("Hello")
False

endswith

检查字符串是否以obj结束,如果是返回True,否则返回 False.

mystr.endswith(obj)

lower

转换 mystr 中所有大写字符为小写

mystr.lower()  

upper
转换mystr中的小写字母为大写

mystr.upper()    

ljust

返回一个原字符串左对齐,并使用空格填充至长度width的新字符串。当width小于字符串长度,不会切片

mystr.ljust(width) 

示例:

>>> mystr = "hello world"
>>> mystr.ljust(15)
'hello world    '
>>> mystr.ljust(6)
'hello world'

center

返回一个原字符串居中,并使用空格填充至长度 width 的新字符串

mystr.center(width)

lstrip

删除mystr左边的空白字符。

mystr.lstrip()

rstrip

删除 mystr 字符串末尾的空白字符。

mystr.rstrip()

strip

删除mystr字符串两端的空白字符。

mystr.strip()

rfind

类似于find()函数,不过是从右边开始查找,查找到第一个符合的返回其地址。

mystr.rfind(str, start=0, end=len(mystr))

示例:

>>> mystr = 'hello world python2 and python3'
>>> mystr.rfind("python")
24

rindex

对应的,类似于 index(),不过是从右边开始。

mystr.rindex( str, start=0,end=len(mystr))

partition

把mystr以str分割成三部分,str前,str和str后。

mystr.partition(str)

示例:

>>> mystr = 'hello world python2 and python3'
>>> mystr.partition('python')
('hello world ', 'python', '2 and python3')

rpartition

类似于partition()函数,不过是从右边开始。

mystr.rpartition(str)

splitlines

按照行分隔,返回一个包含各行作为元素的列表。

mystr.splitlines()  

示例:

>>> mystr = 'hello\nworld'
>>> print mystr
hello
world
>>> mystr.splitlines()
['hello', 'world']

isalpha

如果mystr所有字符都是字母则返回True,否则返回False。

mystr.isalpha() 

isdigit

如果mystr所有字符都是数字则返回True,否则返回False。

mystr.isdigit() 

isalnum

如果mystr所有字符都是字母或数字则返回True,否则返回False。

mystr.isalnum()

isspace

如果mystr中只包含空格,则返回True,否则返回False。

mystr.isspace()

join

str中每个字符后面插入mystr,构造出一个新的字符串。

mystr.join(str)

示例1:

>>> mystr = ' '
>>> str = 'abc'
>>> mystr.join(str)
'a b c'

示例2:

>>> mystr = ['xixi', 'haha']
>>> str = 'abc'
>>> str.join(mystr)
'xixiabchaha'

相关文章

网友评论

      本文标题:Python基础(二)

      本文链接:https://www.haomeiwen.com/subject/hugwuxtx.html