1. 程式人生 > >python入門7 字符串操作

python入門7 字符串操作

digi length 內容 art star pytho bstr 字符替換 使用

字符串操作

#coding:utf-8
#/usr/bin/python
"""
2018-11-03
dinghanhua
字符串操作
"""

‘‘‘字符串是字符元素組成的序列
序列可使用索引,索引:從前往後 0 1 2...,從後往前-1,-2...
‘‘‘
str =i love python

‘‘‘長度len(str)‘‘‘
print(length of str:, len(str))

‘‘‘索引str[index]
index從0到len()-1‘‘‘

print(str[0],str[-1],str[3])
#print(str[100]) # 索引越界IndexError: string index out of range
print(遍歷輸出每個字符:) for index in range(0,len(str)): print(str[index]) #0,len-1 print(反向輸出: ) #for for index in range(1,len(str)+1): print(str[index*-1]) #-1到-len #while i=-1 while i>=-len(str): print(str[i]) i-=1

‘‘‘切片
str[頭索引:尾索引:步長],
步長默認1,包含頭不包含尾
切片不改變原字符串
‘‘‘
slice = str[:3] #
0-2 print(str,slice) print(str[:],str[::2],str[5:],str[2:7],str[1:-1]) print(越界取: ,str[3:100]) print(str is str[:]) #不可變類型地址相同 ‘‘‘字符串翻轉‘‘‘ reversestr = str[::-1] print(reversestr)

‘‘‘ ‘string‘.join(str) 用string將str每個字符連接起來‘‘‘
strjoin = ~.join(str)
print(strjoin)

‘‘‘* 字符串重復輸出‘‘‘
strmul = str*3
print
(strmul) print(-*50) #分割線

‘‘‘字符替換‘‘‘
strreplace = strjoin.replace(~,--,7) #替換最多7次
print(strreplace)

‘‘‘查找字符或子串‘‘‘
index = str.find(python)
print(index) #找到了返回首個匹配字串索引
index = str.find(python,7,10) #從索引7到10之間找
print(index) #沒找到返回-1

index=str.index(o)
print(index) #找到了返回首個匹配字串索引
#index=str.index(‘oll‘)
#print(index) #找不到拋出異常ValueError: substring not found

‘‘‘字符串分割‘‘‘
li = strreplace.split(--)
print(li)
li = strreplace.split() #默認空格
print(li)

‘‘‘將id參數值替換成100‘‘‘
str = id=2&random=35318759314
‘‘‘找到id參數的開始索引和結束索引,切片,替換‘‘‘
begin_index = str.find(id=)
if begin_index != -1:
    end_index = str.find(&,begin_index) #從id=後開始查找&
    strnew = str.replace(str[begin_index : end_index],id=100) #切片然後替換
    print(strnew)

‘‘‘分割,查找替換,連接‘‘‘
li = str.split(&)
print(li)
for i in (0,len(li)):
    if li[i].startswith(id=):
        li[i] = id=100
        break
print(li)
strnew2 = &.join(li)
print(strnew2)

‘‘‘大小寫、去空格、內容判定等‘‘‘
print(str.upper(),str.isupper(),
      str.lower(),str.islower(),
      str.capitalize(), str.istitle() )

print(  test  .strip(),
        test  .lstrip(),
        test  .rstrip())

str=1314432 target test tick 
print(str.isalnum(),
      str.isalpha(),
      str.isdigit(),
      str.isspace())
print(str.count(3),
      str.startswith(131),
      str.endswith(f))

練習題:

#找出第一個不重復的字符
for char in str:
    if str.count(char) == 1:
        print(char,str.index(char))
        break

#去除重復字符
strnew = ‘‘
for char in str:
    if char not in strnew:
        strnew += char
print(strnew)

python入門7 字符串操作