Python 字符串及基本语句

1、braek

break: 某一条件满足的时候,退出循环,不再执行后续重复的代码
在循环体内部,我们可以增加额外的条件,在需要的时候,跳出整个循环

i = 0
while i <10:
if i == 3:
break
print i
i +=1
print ‘over’
这里写图片描述

2、continue

continue:某一条件满足的时候,不执行后续重复的代码,其他条件都要执行
这里写图片描述

3、判断字符串里面的每个元素是否为什么类型

一旦有一个元素不满足,就返回False
print ‘123’.isdigit()
print ‘123abc’.isdigit()
print ‘Hello’.istitle()
print ‘HeLlo’.istitle()
print ‘hello’.upper()
print ‘hello’.islower()
print ‘HELLO’.lower()
print ‘HELLO’.isupper()
print ‘hello’.isalnum()
print ‘123’.isalpha()
print ‘qqq’.isalpha()
这里写图片描述

字符串开头和结尾匹配

定义一个字符串s,判断s是否以xxx结尾。
print s.endswith(‘.xxx’)
定义一个字符串s,判断s是否以xxx开头。
print s.startswith(‘xxx’)

s = ‘hello.jpg’
print s.endswith(‘.png’)

url1 = ‘http://www.baidu.com
url2 = ‘file:///mnt’
print url1.startswith(‘http://’)
print url2.startswith(‘f’)
这里写图片描述

字符串的分离和连接

split对于字符串进行分离,分割符为’.’
例如:
s = ‘172.25.254.250’
s1 = s.split(‘.’)
print s1
#####字符串的索引
例如:
s = ‘hello world’
print len(s)
find找到字符串 并返回最小的索引
print s.find(‘hello’)
这里写图片描述

字符串的定义方式

a = “hello”
b = ‘westos’
c = “what’s up”
d = “””
用户管理
1.添加用户
2.删除用户
3.显示用户
“””
print a
print b
print c
print d
这里写图片描述

字符串的搜索与替换

find找到字符串 并返回最小的索引
s = ‘hello world’
print len(s)
print s.find(‘hello’)
print s.find(‘world’)
print s.replace(‘hello’,’westos’)
这里写图片描述

字符串的特性

定义一个字符串s

s = ‘hello’

1、索引:0,1,2,3,4 索引值是从0开始

print s[0]
print s[1]

2、 切片

## 切片的规则:s[start:end:step] 从start开始到end-1结束,步长:step
print s[0:3]
print s[0:4:2]

3、 显示所有字符

print s[:]

4、显示前3个字符

print s[:3]

5、 对字符串倒叙输出

print s[::-1]

6、除了第一个字符以外,其他全部显示

print s[1:]

7、重复

print s * 10

8、连接

print ‘hello ’ + ‘world’

9、成员操作符

print ‘q’ in s
print ‘he’ in s
print ‘aa’ in s
这里写图片描述

字符串的统计

print ‘helloooo’.count(‘o’)
print ‘helloooo’.count(‘oo’)
print ‘helloooo’.count(‘ooo’)
print ‘helloooo’.count(‘oooo’)
这里写图片描述

while语句

while 条件():
条件满足时,做的事情1
条件满足时,做的事情2
……
例:
1.定义一整数变量,记录循环的次数
2.开始循环
3.希望循环内执行的代码
i = 1
while i <= 3:
print ‘hello python’
# 处理计数器
# i = i +1
i += 1
这里写图片描述

while定义死循环

while True:
print ‘hello python’

结果就是一直循环,死循环。
求1~100累加和

1.定义一个整数记录循环的次数
i = 0
2.定义最终结果的变量
result = 0
3.开始循环
while i <= 100:
print i
# 4.每次循环都让result这个变量和i这个计数器相加
result += i # result = result + i
# 处理计数器
i += 1
print ‘0~100之间的数字求和的结果是 %d’ %result
这里写图片描述

求1~100中偶数的累加和

i = 0
result = 0
while i <= 100:
if i % 2 == 0:
print i
result +=i
i += 1
print ‘0~100之间的偶数累加的结果是 %d’ %result
这里写图片描述

python中的计数方法

常见的计数方法有两种,可以分为
自然计数法(从1开始) – 更符合人类的习惯
程序计数法(从0开始) – 几乎所有的程序语言都选择从0开始计数
因此,大家在编写程序时,应该尽量养成习惯:除非需求的特殊要求,否则循环的计数从0开始

for语句

for 循环使用的语法
for 变量 in range(10):
循环需要执行的代码

猜你喜欢

转载自blog.csdn.net/weixin_41922887/article/details/82151891