Python 常用工具

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/shuzhuchengfu/article/details/102476807

Python 常用工具

检查重复元素

def all_unique(list_data):
    """检查重复元素"""
    return len(list_data) == len(set(list_data))


if __name__ == "__main__":
    a = [1, 2, 3, 4, 5, 6]
    b = [1, 2, 1, 3, 2, 3, 5, 5, 6]
    print(all_unique(a))  # True
    print(all_unique(b))  # False

判断两个字符串排序是否取反

from collections import Counter


def anagram(first, second):
    """判断两个字符串排序是否取反"""
    return Counter(first) == Counter(second)


if __name__ == "__main__":
    print(anagram("1234a", "a4321"))  # True
    print(anagram("1234a", "aa321"))  # False

计算字符串字节大小

def byte_size(string):
    """计算字符串字节大小"""
    return len(string.encode("utf-8"))


if __name__ == "__main__":
    print("字节大小为:%d" % byte_size("hello world"))  # 字节大小为:11

重复打印字符串 N 次

if __name__ == "__main__":
    """重复打印字符串 N 次"""
    print("hello " * 10) # hello hello hello hello hello hello hello hello hello hello

首字母大写

if __name__ == "__main__":
    """首字母大写"""
    print("hello ".title())  # Hello 

未完待续

猜你喜欢

转载自blog.csdn.net/shuzhuchengfu/article/details/102476807
今日推荐