python字符串介绍_python字符串详解
必選掌握
#isupper判斷字符串是否全部都是大寫
str1 = 'Hello,world'
str2 = 'HELLO,WORLD'
print(str1.isupper()) False
print(str2.isupper()) True
#islower判斷字符串是否全部都是小寫
str1 = 'Hello,world'
str2 = 'hello,world'
print(str1.islower()) False
print(str2.islower()) True
#isalnum判斷字符串里是否有數(shù)字、字母、漢字.(或判斷字符串里是否有特殊字符)
str1 = '11122333aaah郝'
str2 = '11122333/qaaa'
print(str1.isalnum()) True
print(str2.isalnum()) false
#isdigit判斷字符串里面是否是整型
str1 = '123'
print(str1.isdigit())
True
#upper()方法把字符串全部變成大寫
str = 'Hello,World'
print(str.upper())
HELLO,WORLD
#startswith判斷字符串開頭是否為He
print(str1.startswith('He'))
#endswith判斷字符串結(jié)尾是否為ld
print(str1.endswith('ld'))
#index取字符串o的下標(biāo),如果沒有這個(gè)字符會(huì)報(bào)錯(cuò)
str1 = 'Hello,World'
print(str1.index('o'))
4
print(str1.rindex('o'))
7
#find取字符串o的下標(biāo),如果沒有這個(gè)字符返回-1
str1 = 'Hello,World'
print(str1.find('o'))
4
print(str1.rfind('o'))
7
print(str1.find('y'))
-1
#isalpha判斷字符串里是英文或漢字
str1 = 'Hello,World'
print(str1.isalpha())
false
#count統(tǒng)計(jì)字符串里l字符的個(gè)數(shù)
print(str1.count('l'))
3
#istitle判斷是否是抬頭
抬頭判斷標(biāo)準(zhǔn):連續(xù)不間斷單詞首字母大寫,其余為小寫,否則為false
print(str1.istitle())
True
#把一個(gè)字符串變成抬頭
print(str1.title())
#isspace判斷字符串是否是純空格
str1 = ''"
str2 = '' "
print(str1.isspace())
false
print(str2.isspace())
Ture
# replace替換字符串o成sb,并且只替換1次
str1 = 'Hello,world'
res = str1.replace('o','sb',1)
print(res)
Hellsb,world
#把一個(gè)可迭代對(duì)象(列表,元組,集合,字典,字符串)變成字符串,表中數(shù)據(jù)類型為字符串
res = ''.join(['abc','123','吉喆'])
print(res)
print(type(res))
abc123吉喆
# str1 = '192.168.250.250'
把一個(gè)字符串從左往右切分變成列表(.代表切分點(diǎn),1代表切分1次)
res = str1.split('.',1)
print(res)
['192', '168.250.250']
#把一個(gè)字符串從右往左切分變成列表(.代表切分點(diǎn),1代表切分1次)
res = str1.rsplit('.',1)
print(res)
['192.168.250', '250']
#去除字符串左右兩邊指定的字符(注意:必須為兩邊邊界)
str1 = '++++++Hello,World====='
res = str1.strip('=')
print(res)
++++++Hello,World
print(str1.strip('+'))
Hello,World=====
#去除字符串右邊指定的字符
res = str1.rstrip('=')
print(res)
#去除字符串左邊指定的字符
str1.lstrip('+')
#format將字符串格式化,可以有以下3種格式
str1 = 'my name is {},my age is {}'
res = str1.format('吉喆', '23')
str1 = 'my name is {1},my age is {0}'
res = str1.format('23', '李凱')
str1 = 'my name is {name},my age is {age}'
res = str1.format(name='李凱', age='23')
print(res)
#%s,%d,%f可以格式化字符串
str1 = 'my name is %s, my age is %s'
res = str1 % ('吉喆', 23)
print(res)
my name. is 吉喆, my age is 23
#利用索引或者下標(biāo)取值,超出范圍報(bào)錯(cuò)
str1 = 'Hello,World'
print(str1[-100])
#字符串的拼接
print(str1[4]+str1[5])
o,
print('1'+'2')
12
#切片
str1 = 'Hello,World'
res = str1[2:5]#正向切片顧頭不顧尾
print(res)
llo
# res = str1[-4:-1]#顧尾不顧頭
print(res)
rld
# res = str1[:3]#索引為3往右的字符不要了(包括下標(biāo)為3的字符)
print(res)
Hel
# res = str1[3:]#索引為3往左的字符不要了(不包括下標(biāo)為3的字符)
print(res)
lo,World
# res = str1[::2]#步長(zhǎng)為2,隔一個(gè)字符取一個(gè)字符
print(res)
HloWrd
總結(jié)
以上是生活随笔為你收集整理的python字符串介绍_python字符串详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 孕妇电子计算机房辐射,孕妇机房辐射大吗
- 下一篇: 大数据的反思