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

python入門7 字串操作

 

字串操作

 

#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)