利用切片
str1 = "hello world!"
print(str1[::-1])
利用reduce函数实现
from functools import reduce
str1 = "hello world!"
print(reduce(lambda x, y : y+x, str1))
str1 = "123455"
def fun(string):
print("%s" % string == string[::-1] and "YES" or "NO")
if __name__ == '__main__':
fun(str1)
str1 = "i love you!"
print(str1.title())# 单词首字母大写
print(str1.upper())# 所有字母大写
print(str1.lower())# 所有字母小写
print(str1.capitalize())# 字符串首字母大写
str1 = "i love you!"
print(str1.split())
# print(str1.split('\')) 则是以\为分隔符拆分
str1 = " i love you! "
print(str1.strip())
返回的是字符串类型
str1 = ["123", "123", "123"]
print(''.join(str1))
str1 = "python"
list1 = [1, 2, 3]
# 乘法表述
print(str1 * 2)
print(list1 * 2)
# 输出
# pythonpython
# [1, 2, 3, 1, 2, 3]
#加法表述
str1 = "python"
list1 = [1, 2, 3]
str1_1 = ""
list1_1 = []
for i in range(2):
str1_1 += str1
list1_1.append(list1)
print(str1_1)
print(list1_1)
# 输出同上
# 修改每个列表的值
list1 = [2, 2, 2, 2]
print([x * 2 for x in list1])
# 展开列表
list2 = [[1, 2, 3], [4, 5, 6], [1]]
print([i for k in list2 for i in k])
# 输出 [1, 2, 3, 4, 5, 6, 1]
x = 1
y = 2
x, y = y, x
调用collections中的Counter类
from collections import Counter
list1 = ['1', '1', '2', '3', '1', '4']
count = Counter(list1)
print(count)
# 输出 Counter({'1': 3, '2': 1, '3': 1, '4': 1})
print(count['1'])
# 输出 3
print(count.most_common(1))# 出现最多次数的
# [('1', 3)]
str1 = "123456"
# 方法一
list_1 = list(map(int, str1))
#方法二
list_2 = [int(i) for i in str1]
str1 = "123456"
list1 = [1, 2, 3, 4, 5]
for i, j in enumerate(str1):
print(i, j)
'''
输出
0 1
1 2
2 3
3 4
4 5
5 6
'''
str1 = "123456"
list1 = [1, 2, 3, 4, 5]
for i, j in enumerate(list1):
print(i, j)
# 输出同上
import time
start = time.time()
for i in range(1999999):
continue
end = time.time()
print(end - start)
# 输出 0.08042168617248535
sys.getsizeof()函数
import sys
str1 = "123456"
print(sys.getsizeof(str1))
# 输出 55
dirt1 = {
'a':2, 'b': 3}
dirt2 = {
'c':3, 'd': 5}
# 方法一
combined_dict = {
**dirt1, **dirt2}
print(combined_dict)
# 输出 {'a': 2, 'b': 3, 'c': 3, 'd': 5}
# 方法二
dirt1 = {
'a':2, 'b': 3}
dirt2 = {
'c':3, 'd': 5}
dirt1.update(dirt2)
print(dirt1)
# 输出同上
list1 = [1, 2, 3, 4, 5, 6]
print('%s' % len(list1) == len(set(list1)) and "NO" or "YES")