1.将"hello world"转换为首字母大写"Hello World"。
print("hello world".title())
>>>Hello World
2.如何检测字符串中只含有数字,True代表都是数字?
print("12ab".isdigit())
>>>False
print("123".isdigit())
>>>True
3.如何将一串字符串进行反转
print("abcdefg"[::-1])
>>>gfedcba
4.如何去掉字符串的前后空格?
print(" abcdefg ".strip())
>>>abcdefg
5.获取字符串的最后两个字符。
print("abcdefg"[-2::])
>>>fg
6.将字符串转换为小写。
print("AbcdE".lower())
>>>abcde
- List = [1,2,2,1,3,4,5,4],对 List 列表元素去重.
List = [1,2,2,1,3,4,5,4]
print(list(set(List)))
>>>[1, 2, 3, 4, 5]
8.实现 "1,2,3" 变成 ["1","2","3"]
s = "1,2,3"
print(s.split(","))
>>>['1', '2', '3']
9.给定两个 list,A 和 B,如何找出相同元素和不同元素。
A = [1, 2, 3, 4, 5, 6]
B = [2, 3, 7, 8, 9]
print(set(A) & set(B))
print(set(A) ^ set(B))
>>>{2, 3}
{1, 4, 5, 6, 7, 8, 9}
10.随机打乱一个列表A=[1,2,3,4,5]的元素。
import random
A = [1, 2, 3, 4, 5]
random.shuffle(A)
print(A)
>>>[1, 5, 4, 3, 2]
- [[1,2],[3,4],[5,6]] 一行代码展开该列表,得出 [1,2,3,4,5,6].
l = [[1,2],[3,4],[5,6]]
x=[j for i in l for j in i]
print(x)
>>>[1, 2, 3, 4, 5, 6]
12.如何交换字典的键和值
A = {"A": "a", "B": "b"}
new_A= dict(zip(A.values(), A.keys()))
print(new_A)
>>>{'a': 'A', 'b': 'B'}