PEP8을 준수하고 E501을 방지하는 매우 긴 문자열을 작성하는 방법
PEP8이 파이썬 프로그램에 대해 80 열 규칙 이하로 유지할 것을 제안함에 따라 긴 문자열로 어떻게 그것을 준수 할 수 있습니까?
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
이것을 다음 줄로 확장하는 방법은 무엇입니까?
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
암시 적 연결이 가장 깨끗한 솔루션 일 수 있습니다.
s = "this is my really, really, really, really, really, really," \
" really long string that I'd like to shorten."
편집 반영 나는 줄 연속 대신 대괄호를 사용하는 Todd의 제안이 그가주는 모든 이유에 더 낫다는 것에 동의합니다. 내가 가진 유일한 주저는 괄호로 묶인 줄과 튜플을 혼동하기가 비교적 쉽다는 것입니다.
또한 인접한 문자열 상수가 자동으로 연결되므로 다음과 같이 코딩 할 수도 있습니다.
s = ("this is my really, really, really, really, really, really, "
"really long string that I'd like to shorten.")
더하기 부호는 없으며 예제 형식에 따라 쉼표와 공백을 추가했습니다.
개인적으로 나는 백 슬래시를 좋아하지 않으며 어딘가에서 더 명백한이 형식을 선호하여 사용이 실제로 사용되지 않는 곳을 읽는 것을 상기합니다. "명시적인 것이 묵시적인 것보다 낫습니다."
백 슬래시는 실제로 줄 바꿈 문자를 벗어나기 때문에 덜 명확하고 덜 유용하다고 생각합니다. 필요한 경우 줄 끝 주석을 붙일 수 없습니다. 연결된 문자열 상수를 사용하여이 작업을 수행 할 수 있습니다.
s = ("this is my really, really, really, really, really, really, " # comments ok
"really long string that I'd like to shorten.")
PEP8 링크를 첫 번째 결과로 반환하는 "python line length"라는 Google 검색을 사용했지만이 주제에 대한 또 다른 좋은 StackOverflow 게시물에 대한 링크도 있습니다. " Python PEP-8에서 최대 줄 길이를 79 자로 지정해야하는 이유는 무엇입니까? "
또 다른 좋은 검색 문구는 "python line continuation"입니다.
귀하의 질문에서 가장 중요한 단어는 "제안"이었습니다.
코딩 표준은 재미있는 것입니다. 그들이 제공하는 지침은 종종 작성 될 때 (예를 들어 대부분의 터미널이 한 줄에 80자를 초과 할 수 없음) 아주 좋은 근거를 갖지만, 시간이 지남에 따라 기능적으로 폐기되었지만 여전히 엄격하게 준수합니다. 여기서해야 할 일은 코드의 가독성과 유지 가능성에 대한 특정 제안을 "파괴"하는 상대적인 장점을 평가하는 것입니다.
죄송합니다. 귀하의 질문에 직접 답변하지 않습니다.
당신은 공간을 잃었고, 아마도 줄 연속 문자가 필요할 것입니다. \
.
s = "this is my really, really, really, really, really, really" + \
" really long string that I'd like to shorten."
또는:
s = "this is my really, really, really, really, really, really" \
" really long string that I'd like to shorten."
Parens는 줄 연속 대신 작동하지만 튜플이 있다고 생각하고 쉼표를 잊어 버린 사람이 위험 할 수 있습니다. 예를 들어 보자.
s = ("this is my really, really, really, really, really, really"
" really long string that I'd like to shorten.")
대:
s = ("this is my really, really, really, really, really, really",
" really long string that I'd like to shorten.")
파이썬의 동적 타이핑을 사용하면 코드가 어느 쪽이든 실행될 수 있지만 의도하지 않은 결과로 잘못된 결과가 생성 될 수 있습니다.
백 슬래시 :
s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."
또는 parens로 감싸십시오 :
s = ("this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten.")
를 사용하면 \
명령문을 여러 줄로 확장 할 수 있습니다.
s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."
작동해야합니다.
이것들은 모두 훌륭한 답변이지만 "암시 적으로 연결된"문자열을 편집하는 데 도움이되는 편집기 플러그인을 찾을 수 없으므로 패키지를 작성하여 더 쉽게 만들었습니다.
이 오래된 스레드를 방황하는 사람이 체크 아웃하려면 pip (설치 단락)에서. html과 같이 여러 줄 문자열을 형식화합니다 (공백, 두 개의 줄 바꿈, 줄 사이의 공백에 대한 걱정 없음).
from paragraphs import par
class SuddenDeathError(Exception):
def __init__(self, cause: str) -> None:
self.cause = cause
def __str__(self):
par(
f"""
Y - e - e - e - es, Lord love you! Why should she die of
influenza? She come through diphtheria right enough the year
before. I saw her with my own eyes. Fairly blue with it, she was.They
all thought she was dead; but my father he kept ladling gin down
her throat til she came to so sudden that she bit the bowl off the
spoon.
What call would a woman with that strength in her have to die of
influenze? What become of her new straw hat that should have
come to me? Somebody pinched it; and what I say is, them as pinched
it done her in."""
)
된다 ...
Y - e - e - e - es, Lord love you! Why should she die of influenza? She come through...
What call would a woman with that strength in her have to die of influenza? What...
모든 것이 (Vim) 'gq'와 쉽게 정렬됩니다.
사용 가능한 옵션 :
- 백 슬래시 :
"foo" \ "bar"
- plus sign followed by backslash:
"foo" + \ "bar"
- brackets:
("foo" "bar")
- brackets with plus sign:
("foo" + "bar")
- PEP8, E502: the backslash is redundant between brackets
Avoid
Avoid brackets with comma: ("foo", "bar")
which defines a tuple.
>>> s = "a" \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = "a" + \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = ("a"
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>> s = ("a",
... "b")
>>> type(s)
<class 'tuple'>
>>> s = ("a" +
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>>
I tend to use a couple of methods not mentioned here for specifying large strings, but these are for very specific scenarios. YMMV...
Multi-line blobs of text, often with formatted tokens (not quite what you were asking, but still useful):
error_message = ''' I generally like to see how my helpful, sometimes multi-line error messages will look against the left border. '''.strip()
Grow the variable piece-by-piece through whatever string interpolation method you prefer:
var = 'This is the start of a very,' var = f'{var} very long string which could' var = f'{var} contain a ridiculous number' var = f'{var} of words.'
Read it from a file. PEP-8 doesn't limit the length of strings in a file; just the lines of your code. :)
Use brute-force or your editor to split the string into managaeble lines using newlines, and then remove all newlines. (Similar to the first technique I listed):
foo = ''' agreatbigstringthatyoudonotwanttohaveanyne wlinesinbutforsomereasonyouneedtospecifyit verbatimintheactualcodejustlikethis '''.replace('\n', '')
I've used textwrap.dedent in the past. It's a little cumbersome so I prefer line continuations now but if you really want the block indent, I think this is great.
Example Code (where the trim is to get rid of the first '\n' with a slice):
import textwrap as tw
x = """
This is a yet another test.
This is only a test"""
print(tw.dedent(x[1:]))
Explanation:
From what I can tell, dedent calculates the indentation based on the white space in the first line of text before a new line. So I added a newline to make it easy to line up the code. To avoid the newline, you'd have to add to the first line of text extra white space so that subsequent lines would have their indentation reduced as you desire. If you wanted to tweak it, you could easily reimplement it using the re
module.
This method has limitations in that very long lines way still be longer than you want in which case other methods that concatenate strings is more suitable.
'Programing' 카테고리의 다른 글
Twitter의 typeahead.js 제안은 스타일이 지정되지 않았습니다 (테두리, 투명 배경 등 없음). (0) | 2020.05.20 |
---|---|
여러 개의 문자열을 다른 여러 개의 문자열로 교체 (0) | 2020.05.20 |
CSS를 사용하여 HTML 요소를 컨테이너를 기준으로 배치 (0) | 2020.05.20 |
사용 (0) | 2020.05.20 |
내 .exe의 경로 가져 오기 (0) | 2020.05.20 |