python-字串操作
阿新 • • 發佈:2019-02-06
- 去空格及特殊符號
s = ' hello, world!'
print s.strip()
print s.lstrip(' hello,')
print s.rstrip('!')
#輸出結果:
#hello, world!
#world!
# hello, world
- 連線字串
#使用 + str1 +=str2
- 查詢字元
S = 'hello'
S1 = 'l'
tmp = S.index(S1)
print tmp
#輸出內容:
#2
- 比較字串
使用函式 print cmp(S1,S2)
#輸出結果可能有:
# -1
# 1
# 0
- 字串中的大小寫轉換
#大寫:
S.upper()
#小寫:
S.lower()
- 翻轉字串
S = 'asdfgh'
S = S[::-1]
print S
#輸出結果:
#hgfdsa
- 查詢字串
S1 = 'asdfgh'
S2 = 'fgh'
print S1.find(S2)
#輸出結果:
#3
- 分割字串
S1 = 'ab,cde,fgh,ijk'
S2 = ','
S1 = S1[S1.find(S2) + 1:]
print S1
#或者:
S = 'ab,cde,fgh,ijk'
print(S.split(','))
#輸出結果:
#cde,fgh,ijk
#['ab','cde','fgh','ijk']
- 計算字串中出現頻次最高的字元
#version 1
import re
from collections import Counter
def get_max_value_v1(text):
text = text.lower()
result = re.findall('[a-zA-Z]', text) # 去掉列表中的符號符
count = Counter(result) # Counter({'l': 3, 'o': 2, 'd': 1, 'h': 1, 'r': 1, 'e': 1, 'w': 1})
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]
#version 2
from collections import Counter
def get_max_value(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]
#version 3
import string
def get_max_value(text):
text = text.lower()
return max(string.ascii_lowercase, key=text.count)
max(range(6), key = lambda x : x>2)
# >>> 3
# 帶入key函式中,各個元素返回布林值,相當於[False, False, False, True, True, True]
# key函式要求返回值為True,有多個符合的值,則挑選第一個。
max([3,5,2,1,4,3,0], key = lambda x : x)
# >>> 5
# 帶入key函式中,各個元素返回自身的值,最大的值為5,返回5.
max('ah', 'bf', key=lambda x: x[1])
# >>> 'ah'
# 帶入key函式,各個字串返回最後一個字元,其中'ah'的h要大於'bf'中的f,因此返回'ah'
max('ah', 'bf', key=lambda x: x[0])
# >>> 'bf'
# 帶入key函式,各個字串返回第一個字元,其中'bf'的b要大於'ah'中的a,因此返回'bf'
text = 'Hello World'
max('abcdefghijklmnopqrstuvwxyz', key=text.count)
# >>> 'l'
# 帶入key函式,返回各個字元在'Hello World'中出現的次數,出現次數最多的字元為'l',因此輸出'l'
'l'
- Count occurrence of a character in a Python string
#T h e M i s s i s s i p p i R i v e r
#[1, 1, 2, 2, 1, 5, 4, 4, 5, 4, 4, 5, 2, 2, 5, 2, 1, 5, 1, 2, 1]
sentence='The Mississippi River'
def count_chars(s):
s=s.lower()
count=list(map(s.count,s))
return (max(count))
print count_chars(sentence)
5