字符串与列表间的转换

字符串转列表的函数–split

功能
  • 将字符串以一定规则切割转成列表
用法
  • string.split(sep=None, maxsplit=-1)
参数
  • sep:切割的规则符号,不填写**,默认空格**,如字符串无空格不分割生成列表

  • maxsplit : 根据切割符号切割的次数, 默认**-1无限制**

返回值
  • 返回一个列表

列表转字符串的函数–join

功能
  • 列表一定规则转成字符串(元组,集合也可以)
用法
  • 'sep'.join(iterable)
参数
  • sep: 生成字符串用来分割列表每个元素的符号
  • iterable: 非数字类型列表或元组或集合
返回值
  • 返回一个字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# coding:utf-8

a = 'abc'
print(a.split())

b = 'a,b,c'
print(b.split(','))

c = 'a|b|c|d'
print(c.split('|', 1))

d = 'a|b|c|d'
print(d.split('|', 2))

f = 'a~b~c'
print(f.split('~', 2))

test = ['a', 'b', 'c']
test_str = '|'.join(test)
print(test_str)

test2 = ['c', 'a', 'b']
print('|'.join(test2))

# test3 = [{'name': 'dewei'}, {'name': 'xiaomu'}]
# print('.'.join(test3))

# test4 = [('a', 'v'), ('a', 'b')]
# print(''.join(test4))

# test5 = [None, True]
# print('.'.join(test5))

sort_str = 'a b c d f i p q c'
sort_list = sort_str.split()
print(sort_list)
sort_list.sort()
print(sort_list)
sort_str = ' '.join(sort_list)
print(sort_str)

sort_str_new = 'abcdfipqc'
print(sort_str_new)
res = sorted(sort_str_new)
print(''.join(res))

seq = ('a', 'b', 'c')
seq2 = {'a', 'b','c'}
print('#'.join(seq))
print('$'.join(seq2), type(seq2))