python string/list转换

python的read、write方法的操作对象都是string。输入、输出和逻辑业务上很多时候都要用到string、list互转。

1.简单用法

import string
str = 'abcde'
list = list(str)
print list
# ['a', 'b', 'c', 'd', 'e']
str_convert = ''.join(list)
print str_convert
# 'abcde'

2.使用split()将一个字符串分裂成多个字符串组成的列表。

str2 = "abc grt werwe"
list2 = str2.split() # or list2 = str2.split(" ")
print list2
# ['abc', 'grt', 'werwe']

str3 = "www.google.com"
list3 = str3.split(".")
print list3
# ['www', 'google', 'com']

3.使用 strip() 方法移除字符串头尾指定的字符。

ids = '1001,1002,1003,1004,'
ids_list = ids.strip(',').split(',')
print ids_list
# ['1001', '1002', '1003', '1004']

4.使用自定字符连接list中的字符串组成一个新字符串

list3 = ['www', 'google', 'com']
str4 = "".join(list3)
print str4
# wwwgooglecom
str5 = ".".join(list3)
print str5
# www.google.com
str6 = " ".join(list3)
print str6
# www google com

done!

猜你喜欢

转载自www.cnblogs.com/zqifa/p/python-string-1.html