Python 是一个可读易用易学的解释型语言,越来越受到广泛大神及小白编程爱好者的喜欢。
废话不多说,直接开整,总结的几个常用的字符串骚操作
1:最简单的字符串翻转操作,采用切片方式
str = "are you ok"
reversed_str = str[::-1]
print(reversed_str)
# ko uoy era
2:首字母大写,所有字母大写,所有字母小写
str = "Are you ok"
# 首字母大写
print(str.title())
# 所有字母大写
print(str.upper())
# 所有字母小写
print(str.lower()
3 判断字符串是否是回文
借助了字符串翻转的判断
str1 = "abcba"
str2 = "abccca"
def fun(funStr):
if funStr != funStr[::-1]:
print(print(funStr + " 不是回文"))
else:
print(funStr + " 是回文")
fun(str1)
fun(str2)
4:字符串拼接
list_of_strings = ['My', 'name', 'is', 'Xiao', 'Ming']
print('/'.join(list_of_strings))
# Output
# My/name/is/Xiao/Ming
5:字符串分割
string_1 = "My name is Xiao Ming"
string_2 = "Xiao/Ming"
print(string_1.split())
# ['My', 'name', 'is', 'Xiao ', 'Ming']
print(string_2.split('/'))
# ['Xiao', ' Ming']
6:重复输出字符串
n = 3 # number of repetitions
my_string = "abcd"
print(my_string*n)
# abcdabcdabcd
7:取组成字符串的元素
str = "aaaabcbcbddncefpppf"
set_str = set(str)
print("".join(set_str))
# pncfabed
8:字符串元素重复次数统计
str = "aaaabcbcbddncefpppf"
count = Counter(str)
# 所有元素的重复次数
print(count)
# Counter({'a': 4, 'b': 3, 'c': 3, 'p': 3, 'd': 2, 'f': 2, 'n': 1, 'e': 1})
# 某个字母的重复次数
print(count['b'])
# 3
# 重复次数最高的
print(count.most_common(1))
# [('a', 4)]