str1 = " hello world, hello, my name is Richard! "
print(str1)
#去除首尾所有空格
print(str1.strip())
#去除首部所有空格
print(str1.lstrip())
#去除尾部所有空格
print(str1.rstrip())
#也可以去掉一些特殊符号
print(str1.strip().rstrip('!')) #方法可以组合使用 先去掉首尾空格 在去掉尾部!
#注意不能直接str.rstrip('!'),因为此时str的尾部是空格,得先去掉空格再去叹号。
#字符串替换
print(str1)
print(str1.replace('hello','how do you do')) #将所有hello都替换为hoe do you do
str2 = " 大家好,我是萌妹子, "
print(str2)
#去除空格和特殊符号
print(str2.strip().lstrip().rstrip(','))
#字符串替换
print(str2.replace('萌妹子','Richard'))
#替换为空串'' 相当于删除
print(str2.replace('大家好,',''))
# hello world, hello, my name is Richard!
# how do you do world, how do you do, my name is Richard!
# 大家好,我是萌妹子,
# 大家好,我是萌妹子
# 大家好,我是Richard,
# 我是萌妹子,
str1 = 'hello,my name is RichardLee.'
#转换小写
print(str1.lower()) #hello,my name is richardlee.
#转换大写
print(str1.upper()) #HELLO,MY NAME IS RICHARDLEE.
#首字母大写
print(str1.capitalize()) #Hello,my name is richardlee.
#每个单词首字母大写
print(str1.title()) #Hello,My Name Is Richardlee.
print(str1)
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)
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_value2(text):
text = text.lower()
return max(string.ascii_lowercase, key=text.count)
str1= get_max_value_v1('aaaaabcdefg')
str2 = get_max_value('abcdbbb')
print(str1)
print(str2)
str22= get_max_value2('cdfffg')
print(str22)
文章目录清除与替换截取/访问连接与切分大小写转换比较与排序计算字符串中出现频率最高的字母清除与替换str1 = " hello world, hello, my name is Richard! "print(str1)#去除首尾所有空格print(str1.strip())#去除首部所有空格print(str1.lstrip())#去除尾部所有空格print(str1.r...