2
3my_string = "ABCDE"
4reversed_string = my_string[::-1]
5
6print(reversed_string)
7
8# Output
9# EDCBAtitle()
方法:
2
3# using the title() function of string class
4new_string = my_string.title()
5
6print(new_string)
7
8# Output
9# My Name Is Chaitanya Baweja
2
3# converting the string to a set
4temp_set = set(my_string)
5
6# stitching set into a string using join
7new_string = ''.join(temp_set)
8
9print(new_string)
10
11# Output
12# acedv
2my_string = "abcd"
3my_list = [1,2,3]
4
5print(my_string*n)
6# abcdabcdabcd
7
8print(my_string*n)
9# [1,2,3,1,2,3,1,2,3]
2my_list = [0]*n # n 表示所需列表的长度
3# [0, 0, 0, 0]
2
3new_list = [2*x for x in original_list]
4
5print(new_list)
6# [2,4,6,8]
2b = 2
3
4a, b = b, a
5
6print(a) # 2
7print(b) # 1split()
方法可以将一个字符串拆分成多个子串,你也可以将分割符作为参数传递进行,进行分割。
2string_2 = "sample/ string 2"
3
4# default separator ' '
5print(string_1.split())
6# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
7
8# defining separator as '/'
9print(string_2.split('/'))
10# ['sample', ' string 2']join()
方法可以将字符串列表组合成一个字符串,下面的代码片段中,我使用,
将所有的字符串拼接到一起:
2
3# Using join with the comma separator
4print(','.join(list_of_strings))
5
6# Output
7# My,name,is,Chaitanya,Baweja
2
3if my_string == my_string[::-1]:
4 print("palindrome")
5else:
6 print("not palindrome")
7
8# Output
9# palindromeCounter
这个类。Counter
会计算每一个元素出现的次数,Counter()
会返回一个字典,元素作为key,出现的次数作为 value。most_common()
这个方法来获取出现字数最多的元素。
2
3my_list = ['a','a','b','b','b','c','d','d','d','d','d']
4count = Counter(my_list) # defining a counter object
5
6print(count) # Of all elements
7# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
8
9print(count['b']) # of individual element
10# 3
11
12print(count.most_common(1)) # most frequent element
13# [('d', 5)]Counter
的一个很有意思的用法是找变位词:Counter
得到的两个对象如果相等,则他们是变位词:
2
3str_1, str_2, str_3 = "acbde", "abced", "abcda"
4cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
5
6if cnt_1 == cnt_2:
7 print('1 and 2 anagram')
8if cnt_1 == cnt_3:
9 print('1 and 3 anagram')
2
3try:
4 print(a/b)
5 # exception raised when b is 0
6except ZeroDivisionError:
7 print("division by zero")
8else:
9 print("no exceptions raised")
10finally:
11 print("Run this always")
2
3for index, value in enumerate(my_list):
4 print('{0}: {1}'.format(index, value))
5
6# 0: a
7# 1: b
8# 2: c
9# 3: d
10# 4: e
2
3num = 21
4
5print(sys.getsizeof(num))
6
7# In Python 2, 24
8# In Python 3, 28update()
方法来合并,在 Python 3.5 中,更加简单,在下面的代码片段中,合并了两个字典,在两个字典存在交集的时候,则使用后一个进行覆盖。
2dict_2 = {'banana': 4, 'orange': 8}
3
4combined_dict = {**dict_1, **dict_2}
5
6print(combined_dict)
7# Output
8# {'apple': 9, 'banana': 4, 'orange': 8}time
这个库,来计算代码执行的时间:
2
3start_time = time.time()
4# Code to check follows
5a, b = 1,2
6c = a+ b
7# Code to check ends
8end_time = time.time()
9time_taken_in_micro = (end_time- start_time)*(10**6)
10
11print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)
2
3# if you only have one depth nested_list, use this
4def flatten(l):
5 return [item for sublist in l for item in sublist]
6
7l = [[1,2,3],[3]]
8print(flatten(l))
9# [1, 2, 3, 3]
10
11# if you don't know how deep the list is nested
12l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
13
14print(list(deepflatten(l, depth=3)))
15# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]random
库,实现了从列表中随机取样。
2
3my_list = ['a', 'b', 'c', 'd', 'e']
4num_samples = 2
5
6samples = random.sample(my_list,num_samples)
7print(samples)secrets
库来实现,更安全。下面的代码片段只能在 Python 3 中运行:
2secure_random = secrets.SystemRandom() # creates a secure random object.
3
4my_list = ['a','b','c','d','e']
5num_samples = 2
6
7samples = secure_random.sample(my_list, num_samples)
8
9print(samples)
2
3list_of_digits = list(map(int, str(num)))
4
5print(list_of_digits)
6# [1, 2, 3, 4, 5, 6]
2 if len(l)==len(set(l)):
3 print("All elements are unique")
4 else:
5 print("List has duplicates")
6
7unique([1,2,3,4])
8# All elements are unique
9
10unique([1,1,2,3])
11# List has duplicates
python培训:http://www.baizhiedu.com/python2019