python循环语句(while)(for)及字符串特性

编程入门 行业动态 更新时间:2024-10-12 16:22:47

一.循环语句

1.range函数

range()函数可以生成一系列的数字
range()函数的用法:
range(stop):0~stop 1
range(start,stop):start~stop 1
range(start,stop,step):start~stop step(步长)

python2:

range(1,5):即刻生成数据,消耗时间并且占用内存
xrange(1,5):先生成一个xrange对象,使用值的时候才生成数据,才占用内存

例:

In [1]: range(5)
Out[1]: [0, 1, 2, 3, 4]
In [2]: range(7)
Out[2]: [0, 1, 2, 3, 4, 5, 6]
In [4]: range(1,10)
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 拿出1~10之间的所有偶数
In [6]: range(2,11,2)
Out[6]: [2,4,6,8,10]
# 拿出1~10之间的所有奇数
In [7]: range(1,11,2)
Out[7]: [1, 3, 5, 7, 9]
python3:

range(1,5):相当于python2中的xrange

2.for 循环

for 变量 in range(10):
循环需要执行的代码
else:
循环结束时需要执行的代码
例:1+2+3+…+100=?

sum = 0
for i in range(1,101):sum = sum + i
print(sum)

3.while循环

while 条件:
条件满足时,做的事情1
条件满足时,做的事情2

例1:循环输出5个’hello,world’

i=1       #定义整数变量,记录循环次数
while i<=5:     #开始循环print('hello,world')i+=1

例2:计算0·100之间的所有偶数之和

i=0
sum=0
while  i<=100:if i%2 == 0:sum+=ii+=1
print('0~100之间的所有偶数之和的结果是 %d' %(sum))

例3:死循环

while True:print('hello python')

4.break,continue,exit()

break:跳出整个循环,不会在执行循环后续的内容
continue:跳出本次循环,continue后面的代码不再执行,但是还是会继续循环
exit():结束程序的运行

for i in range(10):if i == 5:breakprint(i)
输出为:0,1,2,3,4
for i in range(10):if i == 5:continueprint(i)
输出为:0,1,2,3,4,6,7,8,9

二.字符串

1.字符串的定义

字符串就是一系列字符,在python中,用'' , " "括起的都是字符串

2.字符串常用的转义符号

\n:换行
\t:一个tab键
‘’

例:

# 打印guido's
print('guido\'s')
print("guido's")
# 打印"hello guido's python"
print('"hello guido\'s python"')
print("\"hello guido's python\"")
#换行
print('%s\n%s' %(a,b))
#空格
print('%s\t%s' %(a,b))

3.字符串的特性

1.索引

索引:索引是从0开始的

>>>s='hello'
>>>print(s[0])
h
>>>print(s[4])
o
>>>print(s[-1])
o
2.切片

s[start: end :step] 从start开始,到end-1结束,步长为step(默认是1)

>>>s='hello'
>>>print(s)
hello
>>>print(s[0:3])
hel
>>>print(s[0:4:2])
hl
# 显示所有字符
>>>print(s[:])
hello
# 显示前3个字符
>>>print(s[:3])
hel
# 字符串倒序输出
>>>print(s[::-1])
olleh
# 除了第一个字符之外,其他的全部显示
>>>print(s[1:])
ello
5.重复

print(s*10)

6.连接

print('hello '+‘world’)

7.成员操作符
>>>print('he' in s)
True
>>>print('aa' in s)
False
>>>print('he' not in s)
False

4.匹配字符串的开头和结尾

字符串.startwith(‘匹配的字符串’)

url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub/'
url3 = '172.25.254.250/index.html'if url3.startswith(''):print('爬取网页')
else:print('不能爬取网页')
输出为:爬取网页

字符串.endwith(‘匹配的字符串’)

filename='hello.logggh'
if filename.endswith('.log'):print(filename)
else:print('error file')
输出位:error file

5.字符串去掉两边的空格

In [3]: s = '      hello      '                                                
# 去掉两边的空格
In [4]: s.strip()                                                              
Out[4]: 'hello'
# 去掉左边的空格
In [5]: s.lstrip()                                                             
Out[5]: 'hello      '
# 去掉右边的空格
In [6]: s.rstrip()                                                             
Out[6]: '      hello'
In [7]: s = '\nhello      '                                                    
# 去掉\n及空格
In [8]: s.strip()                                                              
Out[8]: 'hello'In [9]: s = '\thello      '                                                    
# 去掉\t及空格
In [10]: s.strip()                                                             
Out[10]: 'hello'
In [11]: s = 'helloh'                                                          
# 去掉左右两边的h
In [12]: s.strip('h')                                                          
Out[12]: 'ello'
# 去掉左边he,右边h
In [13]: s.strip('he')                                                         
Out[13]: 'llo'
# 去掉左边he
In [14]: s.lstrip('he')                                                        
Out[14]: 'lloh'
# 去掉右边h
In [15]: s.rstrip('he')                                                        
Out[15]: 'hello'
In [17]: print('学生管理系统'.center(50,'*'))                                  
**********************学生管理系统**********************In [18]: print('学生管理系统'.ljust(50,'*'))                                   
学生管理系统********************************************In [19]: print('学生管理系统'.rjust(50,'*'))                                   
********************************************学生管理系统

6.字符串的搜索和替换

s.find(sub):判断sub是否在s中,存在返回索引值,不存在返回-1
s.replace(old,new):将s中的old字符串替换为new字符串,并将替换后的新字符串返回
s.count(sub):返回sub在a中出现的次数
例:

In [20]: s = 'hello python,learn python'                                       In [21]: s.find('python')                                                      
Out[21]: 6In [22]: s.rfind('python')                                                     
Out[22]: 19In [23]: s.replace('python','linux')                                           
Out[23]: 'hello linux,learn linux'In [24]: s1 = s.replace('python','linux')                                      In [25]: s1                                                                    
Out[25]: 'hello linux,learn linux'In [26]: s                                                                     
Out[26]: 'hello python,learn python'In [27]: s.count('python')                                                     
Out[27]: 2In [28]: s.count('p')                                                          
Out[28]: 2In [29]: s.count('i')                                                          
Out[29]: 0

7.字符串的分离和拼接

s.split(sep):以sep字符串作为分割符对s进行切割,默认为空格
str.join(seq):以str作为分隔符,将序列seq中的所有元素合并为一个新的字符串

In [30]: ip = '172.25.254.10'                                                  In [31]: ip1 = '1172.25.254.10'                                                In [32]: ip1.split('.')                                                        
Out[32]: ['1172', '25', '254', '10']In [33]: date = '2018-11-18'                                                   In [34]: date.split('-')                                                       
Out[34]: ['2018', '11', '18']In [35]: date.split('.')                                                       
Out[35]: ['2018-11-18']In [37]: date.replace('-','/')                                                 
Out[37]: '2018/11/18'In [38]: ip = ['1172', '25', '254', '10']                                      In [39]: ''.join(ip)                                                           
Out[39]: '11722525410'In [40]: ':'.join(ip)                                                          
Out[40]: '1172:25:254:10'In [41]: '*'.join(ip)                                                          
Out[41]: '1172*25*254*10'

8.字符串大小写判断

判断字符串是否为标题(首字母大写即为标题)

In [1]: 'Hello'.istitle()
Out[1]: True
In [2]: 'hello'.istitle()
Out[2]: False

判断字符串是否全为小写

In [7]: 'heLLo'.islower()
Out[7]: False

判断字符串是否全为大写

In [8]: 'heLLo'.isupper()
Out[8]: False

将字符串全部变为大写

In [3]: 'hello'.upper()
Out[3]: 'HELLO'

将字符串全部变为小写

In [4]: 'heLLo'.lower()
Out[4]: 'hello'

将字符串变为标题

In [5]: 'heLLo'.title()
Out[5]: 'Hello'

将字符串大小写颠倒

In [6]: 'heLLo'.swapcase()
Out[6]: 'HEllO'

9.python常用内置方法

输出最小

In [1]: min(2,4)
Out[1]: 2

输出最大

In [2]: max(2,4)
Out[2]: 4

求和

In [3]: sum(range(1,101))
Out[3]: 5050In [4]: sum(range(2,101,2))
Out[4]: 2550In [5]: sum(range(1,101,2))
Out[5]: 2500

枚举

In [8]: for i,v in enumerate('hello'):...:     print(str(i) + '--------->' + v)...:
0--------->h
1--------->e
2--------->l
3--------->l
4--------->o
In [9]: s1 = 'abc'In [10]: s2 = '123'In [11]: for i in zip(s1,s2):...:     print(i)...:
('a', '1')
('b', '2')
('c', '3')
In [12]: for i in zip(s1,s2):...:     print(''.join(i))...:
a1
b2
c3In [13]: for i in zip(s1,s2):...:     print('-'.join(i))...:
a-1
b-2
c-3

更多推荐

字符串,语句,特性,python

本文发布于:2023-05-28 06:59:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/315183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   语句   特性   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!