python中str与list互换,txt文件的读取,字符串变成列表操作,另存为TXT时从列表变成字符串 python中str与list互换

file = open ("wider_face_train_bbx_gt.txt")
for line in lines:
    print(type(line)) #<type 'str'> #78 221 7 8 2 0 0 0 0
    a=(line.strip()).split("\t") #输出是字符串列表没改动原本的line,
    #原本的line没有改变,<type 'list'>
        a=line.split()  #<type 'list'>返回一个空格隔开的字符列表,
        #上面两行功能一样['78', '221', '7', '8', '2', '0', '0', '0', '0']
        # 都是把读取的TXT,字符串类型的数据变成,列表便于操作
        #保存成TXT文件,需要是转换成字符串类型

        #也有两种方法
        c=str(a[2:5]).replace('[','').replace(']','') #不加str 会错,把列表变成字符串,将字符串中的括号,引   号,逗号全部删除,默认有一个空格将数据分开
        c=c.replace("'",'').replace(',','') #输出7 8 2

#第二种方式
        txt=' '.join(a)#引号中间打出了一个空格。  直接把列表变成字符串操作

python中str与list互换

因为python的read和write方法的操作对象都是string。


而进行一些处理的时候会把string转换成list进行解析,解析后重新写入文件的时候,还得转换成string。


下面我通过例子,来表达如何进行string与list的转换


将string类型转换为list类型


      
      
  1. str = “I am a student”
  2. lis = str.split( ’ ‘)
  3. print lis

输出结果为:


将list类型转换为string类型


      
      
  1. str2 = ' '.join(lis)
  2. print str2

输出结果为:



则完成了二者类型的转换!

完整代码如下:


      
      
  1. str = "I am a student"
  2. lis = str.split( ' ')
  3. print lis
  4. str2 = ' '.join(lis)
  5. print str2



因为python的read和write方法的操作对象都是string。


而进行一些处理的时候会把string转换成list进行解析,解析后重新写入文件的时候,还得转换成string。


下面我通过例子,来表达如何进行string与list的转换


将string类型转换为list类型


  
  
  1. str = “I am a student”
  2. lis = str.split( ’ ‘)
  3. print lis

输出结果为:


将list类型转换为string类型


  
  
  1. str2 = ' '.join(lis)
  2. print str2

输出结果为:



则完成了二者类型的转换!

完整代码如下:


  
  
  1. str = "I am a student"
  2. lis = str.split( ' ')
  3. print lis
  4. str2 = ' '.join(lis)
  5. print str2



猜你喜欢

转载自blog.csdn.net/m0_37192554/article/details/82656522