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)

猜你喜欢

转载自www.cnblogs.com/dinghanhua/p/9903289.html