Nice programing

목록을 문자열로 변환

nicepro 2020. 11. 27. 21:25
반응형

목록을 문자열로 변환


이 질문에 이미 답변이 있습니다.

파일에서 일부 데이터를 추출하여 두 번째 파일에 쓰고 싶습니다. 하지만 내 프로그램이 오류를 반환합니다.

sequence item 1: expected string, list found

이것은 write()문자열을 원하지만 목록을 받고 있기 때문에 발생하는 것처럼 보입니다 .

그래서,이 코드에 대해서, 어떻게 목록을 변환 할 수 있습니다 buffer내가의 내용을 저장할 수 있도록 문자열 buffer로를 file2?

file = open('file1.txt','r')
file2 = open('file2.txt','w')
buffer = []
rec = file.readlines()
for line in rec :
    field = line.split()
    term1 = field[0]
    buffer.append(term1)
    term2 = field[1]
    buffer.append[term2]
    file2.write(buffer)  # <== error
file.close()
file2.close()

시도해보십시오 str.join:

file2.write(' '.join(buffer))

문서 내용 :

반복 가능한 이터 러블에서 문자열의 연결 인 문자열을 반환합니다. 요소 사이의 구분자는이 메서드를 제공하는 문자열입니다.


''.join(buffer)

file2.write( str(buffer) )

설명 : str(anything)모든 파이썬 객체를 문자열 표현으로 변환합니다. 를 수행하면 얻는 출력과 유사 print(anything)하지만 문자열로 표시됩니다.

참고 : 이것은 아마도 OP가 원하는 것이 아닙니다.의 요소 buffer가 연결 되는 방식을 제어 할 수 없기 때문입니다 ( ,요소 사이에 배치됨).하지만 다른 사람에게 유용 할 수 있습니다.


buffer=['a','b','c']
obj=str(buffer)
obj[1:len(obj)-1]

출력으로 " 'a', 'b', 'c'"를 제공합니다.


file2.write(','.join(buffer))

방법 1 :

import functools
file2.write(functools.reduce((lambda x,y:x+y), buffer))

방법 2 :

import functools, operator
file2.write(functools.reduce(operator.add, buffer))

방법 3 :

file2.write(''.join(buffer))

# it handy if it used for output list
list = [1, 2, 3]
stringRepr = str(list)
# print(stringRepr)
# '[1, 2, 3]'

에서 공식 파이썬 프로그래밍 질문 파이썬 3.6.4에 대한 :

What is the most efficient way to concatenate many strings together? str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

To accumulate many str objects, the recommended idiom is to place them into a list and call str.join() at the end:

chunks = []
for s in my_strings:
    chunks.append(s)
result = ''.join(chunks)

(another reasonably efficient idiom is to use io.StringIO)

To accumulate many bytes objects, the recommended idiom is to extend a bytearray object using in-place concatenation (the += operator):

result = bytearray()
for b in my_bytes_objects:
    result += b

참고URL : https://stackoverflow.com/questions/2906092/converting-a-list-to-a-string

반응형