1.去空格及特殊符號:
s = ' How are you!'
print(s.strip()) # 去除字符串兩邊的空格
print(s.lstrip(' How ')) # 從字符串左邊去掉‘ How ’,若字符串左邊不是以‘ How ’開頭,則無效
print(s.rstrip('!')) # 從字符串右邊去掉‘!’,若字符串右邊不是以‘!’結尾,則無效
*******
輸出結果:
How are you!
are you!
How are you
2.連接字符串:
s1='abc'
s2='def'
s3=s1+s2
print(s3)
3.判斷字符串是否屬於另一個字符串子集
s1 = 'How are you!'
s2 = 'you'
s_index=s1.index(s2) # 獲取s2在s1中的位置,若s_index<0則s1不包含s2
print(s_index)
print(s2 in s1) #若s1包含s2則返回True,否則返回False
*****
輸出結果:
8
True
4.比較字符串
import operator
s1 = 'How are you'
s2 = 'How old are you'
print(operator.eq(s1,s2)) # 比較兩個字符串,等同於s1==s2,若相等返回True否則返回False
print(operator.lt(s1,s2)) # 等同於s1<s2
print(operator.le(s1,s2)) # 等同於s1≤s2
print(operator.ne(s1,s2)) # 等同於s1!=s2
print(operator.gt(s1,s2)) # 等同於s1>s2
print(operator.ge(s1,s2)) # 等同於s1≥s2
*****
輸出結果:
False
True
True
True
False
False
5.字符串中大小寫轉換
s1='AbCdEfG'
print(s1.upper()) # 全部字符轉爲大寫
print(s1.lower()) # 全部字符轉爲小寫
*****
輸出結果:
ABCDEFG
abcdefg
6.反轉字符串:
s1='abcdefg'
print(s1[::-1]) # 翻轉字符串
*****
輸出結果:
gfedcba
7.查找字符串
s1= 'how old are you'
s2 = 'old'
print(s1.find(s2)) # 從s1中找到s2的位置,若不存在返回-1
*****
輸出結果:
4
8.分割字符串
s1='apple,banana,orange,pear'
s_list=s1.split(',') # 將字符串按照,拆分爲一個字符列表
s2=s1[s1.find(','):] # 從第一個,處開始截取字符串
print(s_list)
print(s2)
*****
輸出結果:
['apple', 'banana', 'orange', 'pear']
,banana,orange,pear
9.計算字符串中出現頻次最多的符號
# 方法一
import re
from collections import Counter
def Get_max_value_l(text):
text = text.lower() # 將所有字符轉爲小寫
result = re.findall('[a-z]',text) #獲取字符串中所有字母
count=Counter(result) # 查詢所有字母的個數
count_list = list(count.values())
max_value=max(count_list)
max_list=[]
for k,v in count.items:
if v==max_value:
max_list.append(k)
max_list=sorted(max_list)
return max_list[0]
# 方法二
from collections import Counter
def get_max_value_2(text):
count = Counter([x for x in text.lower() if x.isalpha()])
m = max(count.values())
return sorted([x for (x,y) in count.items() if y == m])[0]
# 方法三
import string
def get_max_value_3(text):
text = text.lower()
return max(string.ascii_lowercase,key=text.count)
10.max函數的用法
max(renge(100),key = lambda x:x>50) # 使用key值導入拉姆達表達式,規定在0-99的數列中,返回大於50的數中得第一個
max('as','bd',key = lambda x : x[1]) # 使用key值導入蘭姆達表達式,將字符串的第二個字符進行對比,返回第二個字符比較大的字符串
max('qwertyuiopasdfghjklzxcvbnm',key='how are you'.count) # 使用key值導入蘭姆達表達式,返回'how are you'中出現次數最多的字符