defmylower(src):
src1 = ''
for i in
src:
if'a'
<= i <= 'z'
: src1 += chr(ord(i) + 32)
else
: src1 +=i
return
src1
#print(mylower('acdejlg'))
defmyupper(src):
src1 = ''
for i in
src:
if'a'
<= i <= 'z'
: src1 += chr(ord(i) - 32)
else
: src1 +=i
return
src1
#print(myupper('acdef'))
第一種思路:defmyfind1(src,sub):
for i in range(len(src)-len(sub)+1):
new_src = src[i:i+len(sub)]
#print(new_src)
if new_src ==sub:
return
i
else
:
return -1
print(myfind1('
abcde123abe
','123a'))
第二種思路:
defmyfind(src,sub):
if len(sub) >len(src):
return -1
for i in
range(len(src)):
if src[i] ==sub[0]:
index =i
for j in
range(len(sub)):
if src[index] !=sub[j]:
break
index += 1
else
:
return
i
else
:
return -1
第一種思路:defmyrfind(src,sub):
#從右往左進行遍歷
for i in range(len(src)-1,-1,-1):
#先找第乙個字元,如果一致,在進行對應切片比較
if sub[0] ==src[i]:
#如果切片出來的結果與子串一致,返回所在的索引值
if sub == src[i:i+len(sub)]:
return
i
#如果沒找到,返回-1
else
:
return -1
#index = myrfind('abc123','c1')
#print(index)
第二種思路:
defmyrfind(src,sub):
if len(sub) >len(src):
return -1
for i in range(-1,-len(src)-1,-1):
if src[i] ==sub[0]:
index =i
for j in
range(len(sub)):
if src[index] !=sub[j]:
break
index += 1
else
:
return len(src) +i
else
:
return -1
#print(myrfind('abcdegabeda','ab'))
defmyisdigit(src):
for ch in
src:
ifnot'0
'<= ch <= '9'
:
return
false
else
:
return
true
print(myisdigit('
123'
))print(myisdigit('
123a
'))
defmypartition(src,sub):
if sub in
src:
#獲取子串在目標字串的索引值
index =myrfind(src,sub)
#切片操作劃分三個元素: 1.str[0:index] 2.sub 3.[index+len(sub):]
return (src[0:index],sub,src[index+len(sub):])
else
:
return (src,'','')#
print(mypartition('abcdef','g'))
print(mypartition('
abcdef
','cd
'))
python 內建函式字串操作
str1 hello,world 通過內建函式len計算字串的長度 print len str1 13 獲得字串首字母大寫的拷貝 print str1.capitalize hello,world 獲得字串每個單詞首字母大寫的拷貝 print str1.title hello,world 獲得字串變...
Python關於字串的內建函式 字串操作)
環境 python3.6.4 1.字串首字母大寫 capitalize s atlan print s.capitalize atlan2.字串全大寫 upper s atlan print s.upper atlan3.字串全小寫 lower s atlan print s.lower atlan...
字串內建函式
方法 描述 string.capitalize 把字串的第乙個字元大寫 string.center width 返回乙個原字串居中,並使用空格填充至長度 width 的新字串 string.count str,beg 0,end len string 返回 str 在 string 裡面出現的次數,...