Python 字符串及基本语句
#####1、break
break: 某一條件滿足的時候,退出循環(huán),不再執(zhí)行后續(xù)重復的代碼
在循環(huán)體內(nèi)部,我們可以增加額外的條件,在需要的時候,跳出整個循環(huán)
i = 0
while i <10:
if i == 3:
break
print i
i +=1
print ‘over’
#####2、continue
continue:某一條件滿足的時候,不執(zhí)行后續(xù)重復的代碼,其他條件都要執(zhí)行
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()
#####字符串開頭和結(jié)尾匹配
定義一個字符串s,判斷s是否以xxx結(jié)尾。
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、 切片
切片的規(guī)則:s[start?step] 從start開始到end-1結(jié)束,步長: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 ‘a(chǎn)a’ in s
#####字符串的統(tǒng)計
print ‘helloooo’.count(‘o’)
print ‘helloooo’.count(‘oo’)
print ‘helloooo’.count(‘ooo’)
print ‘helloooo’.count(‘oooo’)
#####while語句
while 條件():
條件滿足時,做的事情1
條件滿足時,做的事情2
…
例:
1.定義一整數(shù)變量,記錄循環(huán)的次數(shù)
2.開始循環(huán)
3.希望循環(huán)內(nèi)執(zhí)行的代碼
i = 1
while i <= 3:
print ‘hello python’
# 處理計數(shù)器
# i = i +1
i += 1
#####while定義死循環(huán)
while True:
print ‘hello python’
#####結(jié)果就是一直循環(huán),死循環(huán)。
#####求1~100累加和
1.定義一個整數(shù)記錄循環(huán)的次數(shù)
i = 0
2.定義最終結(jié)果的變量
result = 0
3.開始循環(huán)
while i <= 100:
print i
# 4.每次循環(huán)都讓result這個變量和i這個計數(shù)器相加
result += i # result = result + i
# 處理計數(shù)器
i += 1
print ‘0~100之間的數(shù)字求和的結(jié)果是 %d’ %result
#####求1~100中偶數(shù)的累加和
i = 0
result = 0
while i <= 100:
if i % 2 == 0:
print i
result +=i
i += 1
print ‘0~100之間的偶數(shù)累加的結(jié)果是 %d’ %result
#####python中的計數(shù)方法
常見的計數(shù)方法有兩種,可以分為
自然計數(shù)法(從1開始) – 更符合人類的習慣
程序計數(shù)法(從0開始) – 幾乎所有的程序語言都選擇從0開始計數(shù)
因此,大家在編寫程序時,應該盡量養(yǎng)成習慣:除非需求的特殊要求,否則循環(huán)的計數(shù)從0開始
#####for語句
for 循環(huán)使用的語法
for 變量 in range(10):
循環(huán)需要執(zhí)行的代碼
總結(jié)
以上是生活随笔為你收集整理的Python 字符串及基本语句的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python基本知识以及if语句
- 下一篇: Python中if语句练习题