python的快捷代码,每天学一点

1.字符串的翻转
Means1

str = 'hello world'
print(str[::-1])
# dlrow olleh

Means2

from functools import reduce
print(reduce(lambda x,y:y+x,str))
# dlrow olleh

2.判断字符串是否是回文

str = 'serendipity'
str1 = 'abcddcba'

def Prlind(str):
    if str == str[::-1]:
        print('该字符串是回文字符串')
    else:
        print('该字符串不是回文字符串')


Prlind(str)
#该字符串不是回文字符串
Prlind(str1)
#该字符串是回文字符串

3.字母大小写

str = 'i love Python'

print(str.title())  # 所有字母首字母大写  I Love Python

print(str.upper())  # 所有字母大写  I LOVE PYTHON

print(str.capitalize())  # 首字母大写  I love python

4.检查数据的唯一性

lis = [1,4,5,8,8,10]
lis1 = [1,4,5,6,8,10]

def ifunique(str):
    if len(str) != len(set(str)):
        print('not unique')
    else:
        print('unique')

ifunique(lis)
#not unique
ifunique(lis1)
#unique

5.合并字典

dict1 = {
    
    'a':1, 'b':2}
dict2 = {
    
    'c':3, 'd':4}
#方法一(python3用法):
dict1.update(dict2)
print(dict1)
#{'a': 1, 'b': 2, 'c': 3, 'd': 4}
#方法二(python2用法):
combine_dict = {
    
    **dict1,**dict2}
print(combine_dict)
#{'a': 1, 'b': 2, 'c': 3, 'd': 4}

6.将数字字符串转化为数字列表

str = '13579'
#方法1
lis1 = list(map(int,str))
print(lis1)
#[1, 3, 5, 7, 9]
#方法2
lis2 = [int(i) for i in str]
print(lis2)
#[1, 3, 5, 7, 9]
#推荐第二种

7.判断字符串中所含数字是否相同

from collections import Counter

str1 = 'abcdefg'
str2 = 'abcdefg'
str3 = 'bacdefg'

cn_str1 = Counter(str1)
cn_str2 = Counter(str2)
cn_str3 = Counter(str3)

if (cn_str1 == cn_str2) and (cn_str2 == cn_str3):
    print('=====')
else:
    print('!====')
#=====

if (str1 == str2) and (str2 == str3):
    print('=====')
else:
    print('!====')
#!====
Counter函数还可以用来判断字符串中包含的元素是否相同,无论字符串中元素顺序如何,只要包含相同的元素和数量,就认为其是相同的。

8.两值交换

a = 'Tom'
b = 'Cat'

a,b = b,a
print(a+'---'+b)
#Cat---Tom

9.统计各个元素个数

from collections import Counter

list = ['p','e','a','n','u','t','p','p','n','u']
count = Counter(list)
print(count)
#Counter({'p': 3, 'n': 2, 'u': 2, 'e': 1, 'a': 1, 't': 1})
print(count['p'])
#3
print(count.most_common(1))
#[('p', 3)]

10.寻找字符串中的唯一元素

#对于字符串的过滤
str = 'peanutpeant'
print(''.join(set(str)))
#nutaep
#对子列表的过滤
lis1 = [1,5,7,6,1,5,7,6,8,23,11]
print(set(lis1))
{
    
    1, 5, 6, 7, 8, 11, 23} # 字典类型
print(list(set(lis1)))  # 转为列表
#[1, 5, 6, 7, 8, 11, 23]

猜你喜欢

转载自blog.csdn.net/Python_BT/article/details/107943374