python字符串操作

来源:互联网 发布:mac系统u盘制作 编辑:程序博客网 时间:2024/06/06 19:06
    phone = "2004-959-559\n 这是一个电话号码"    print(phone)    phone = phone.replace("\n", "")    phone = re.sub(r'\n',"", phone)    print( phone)

两个方法

但是注意 python 一般是返回型函数,不是在值上改

如果只是:

phone.replace("\n", "")
phone还是更改之前的样子


"   xyz   ".strip()            # returns "xyz"  "   xyz   ".lstrip()           # returns "xyz   "  "   xyz   ".rstrip()           # returns "   xyz"  "  x y z  ".replace(' ', '')   # returns "xyz" 


list与str相互转换

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


str.split()

split翻译为分裂。  split()就是将一个字符串分裂成多个字符串组成的列表。split()当不带参数时以空格进行分割,当代参数时,以该参数进行分割。//---当不带参数时example:st0= '   song    huan     gong    'print(st0.split())结果为:['song', 'huan', 'gong']


原创粉丝点击