Programing

목록을 "올바르게"인쇄하는 방법은 무엇입니까?

crosscheck 2020. 9. 18. 07:36
반응형

목록을 "올바르게"인쇄하는 방법은 무엇입니까?


그래서 목록이 있습니다.

['x', 3, 'b']

그리고 출력은 다음과 같습니다.

[x, 3, b]

파이썬에서 어떻게 할 수 있습니까?

그렇게하면 str(['x', 3, 'b'])따옴표가있는 하나를 얻지 만 따옴표는 원하지 않습니다.


Python 2 :

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

Python 3에서 (여기서는 print더 이상 구문 기능이 아닌 내장 함수) :

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

둘 다 반환 :

[x, 3, b]

이것은 mylist의map() 각 요소에 대해 str을 호출 하는 함수를 사용하여 다음과 같이 하나의 문자열로 결합되는 새로운 문자열 목록을 생성합니다 . 그런 다음 문자열 형식화 연산자가 in 대신 in 문자열을 대체합니다 .str.join()%%s"[%s]"


이것은 간단한 코드이므로 초보자라면 충분히 쉽게 이해할 수 있어야합니다.

    mylist = ["x", 3, "b"]
    for items in mylist:
        print(items)

원하는대로 따옴표없이 모두 인쇄합니다.


Python3을 사용하는 경우 :

print('[',end='');print(*L, sep=', ', end='');print(']')

인쇄 만 사용 :

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

을 사용하는 대신 반복자를 허용하는 map기능이있는 생성기 표현식을 사용하는 것이 좋습니다 join.

def get_nice_string(list_or_iterator):
    return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"

다음 join은 문자열 클래스의 멤버 함수입니다 str. 하나의 인수, 즉 문자열 목록 (또는 반복자)을 취한 다음 모든 요소가 연결된 새 문자열을 반환합니다 (이 경우) ,.


인수에 대해 제거 할 문자가 포함 된 문자열이 뒤에 오는 인수 for translate()메서드사용하여 문자열에서 원하지 않는 모든 문자를 삭제할 수 있습니다 .Nonetabledeletechars

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:

import string

print string.translate(str(lst), None, "'")

Using the string.translate() function will also work in 2.6+, so using it might be preferable.


Here's an interactive session showing some of the steps in @TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)

Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

Using .format for string formatting,

mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))

Output:

[x, 3, b]

Explanation:

  1. map is used to map each element of the list to string type.
  2. The elements are joined together into a string with , as separator.
  3. We use [ and ] in the print statement to show the list braces.

Reference: .format for string formatting PEP-3101


This is another way... maybe a little bit more labourious...

mylist = ['x', 3, 'b']
print('[', end='')
print(*myList, sep=', ', end='')
print(']')

You will remove ´\n´and this way you can concatenate the strings.

참고URL : https://stackoverflow.com/questions/5445970/how-to-properly-print-a-list

반응형