developer tip

파이썬 첫 번째와 마지막 큰 따옴표를 어떻게 제거 할 수 있습니까?

optionbox 2020. 8. 29. 10:47
반응형

파이썬 첫 번째와 마지막 큰 따옴표를 어떻게 제거 할 수 있습니까?


큰 따옴표를 제거하고 싶습니다.

string = '"" " " ""\\1" " "" ""'

string = '" " " ""\\1" " "" "'

내가 사용하려고 rstrip, lstrip그리고 strip('[^\"]|[\"$]')그러나 그것은 작동하지 않았다.

어떻게 할 수 있습니까? 도와 주셔서 감사합니다.


제거하려는 따옴표가 말한대로 항상 "처음과 마지막"이 될 경우 다음을 간단히 사용할 수 있습니다.

string = string[1:-1]


처리하는 모든 문자열에 큰 따옴표가 있다고 가정 할 수없는 경우 다음과 같이 사용할 수 있습니다.

if string.startswith('"') and string.endswith('"'):
    string = string[1:-1]

편집하다:

나는 당신이 방금 사용했던 해요 string여기 예시를 위해하고 유용한 이름이 실제 코드에서 변수 이름으로,하지만 난라는 이름의 모듈이 있음을 경고 할 의무가 기분이 string표준 라이브러리에. 자동으로로드되지는 않지만 사용 import string하는 경우 변수가이를 가려 내지 않는지 확인하십시오.


첫 번째와 마지막 문자를 제거하려면 각각의 경우 해당 문자가 큰 따옴표 인 경우에만 제거를 수행합니다.

import re

s = re.sub(r'^"|"$', '', s)

RE 패턴은 사용자가 지정한 것과 다르며 작업은 sub빈 대체 문자열 ( "대체") ( strip문자열 방법이지만 다른 답변에서 알 수 있듯이 요구 사항과 매우 다른 작업을 수행함)입니다.


중요 : 작은 따옴표 나 큰 따옴표를 제거하기 위해 질문 / 답변을 확장하고 있습니다. 그리고 나는 스트립을 수행하기 위해 두 따옴표가 모두 존재하고 일치해야 함을 의미하는 것으로 질문을 해석합니다. 그렇지 않으면 문자열이 변경되지 않고 반환됩니다.

문자열 표현을 "디 쿼트"하려면 주위에 작은 따옴표 또는 큰 따옴표가있을 수 있습니다 (@tgray의 대답의 확장입니다).

def dequote(s):
    """
    If a string has single or double quotes around it, remove them.
    Make sure the pair of quotes match.
    If a matching pair of quotes is not found, return the string unchanged.
    """
    if (s[0] == s[-1]) and s.startswith(("'", '"')):
        return s[1:-1]
    return s

설명:

startswith여러 대안 중 하나와 일치시키기 위해 튜플을 취할 수 있습니다. 배가 된 괄호에 대한 이유 (())우리가 하나 개의 매개 변수 전달이 너무 ("'", '"')에을 startswith()의 접두어보다는 두 개의 매개 변수를 허용 지정 "'"'"'접두사와 (무효) 시작 위치로 해석됩니다.

s[-1] 문자열의 마지막 문자입니다.

테스트 :

print( dequote("\"he\"l'lo\"") )
print( dequote("'he\"l'lo'") )
print( dequote("he\"l'lo") )
print( dequote("'he\"l'lo\"") )

=>

he"l'lo
he"l'lo
he"l'lo
'he"l'lo"

(나에게 정규 표현식은 읽기가 명확하지 않으므로 @Alex의 대답을 확장하려고 시도하지 않았습니다.)


문자열이 항상 표시되는 경우 :

string[1:-1]

거의 완료되었습니다. http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip 에서 인용

chars 인수는 제거 할 문자 집합을 지정하는 문자열입니다.

[...]

chars 인수는 접두사 또는 접미사가 아닙니다. 오히려 해당 값의 모든 조합이 제거됩니다.

So the argument is not a regexp.

>>> string = '"" " " ""\\1" " "" ""'
>>> string.strip('"')
' " " ""\\1" " "" '
>>> 

Note, that this is not exactly what you requested, because it eats multiple quotes from both end of the string!


If you are sure there is a " at the beginning and at the end, which you want to remove, just do:

string = string[1:len(string)-1]

or

string = string[1:-1]

Remove a determinated string from start and end from a string.

s = '""Hello World""'
s.strip('""')

> 'Hello World'

I have some code that needs to strip single or double quotes, and I can't simply ast.literal_eval it.

if len(arg) > 1 and arg[0] in ('"\'') and arg[-1] == arg[0]:
    arg = arg[1:-1]

This is similar to ToolmakerSteve's answer, but it allows 0 length strings, and doesn't turn the single character " into an empty string.


find the position of the first and the last " in your string

>>> s = '"" " " ""\\1" " "" ""'
>>> l = s.find('"')
>>> r = s.rfind('"')

>>> s[l+1:r]
'" " " ""\\1" " "" "'

in your example you could use strip but you have to provide the space

string = '"" " " ""\\1" " "" ""'
string.strip('" ')  # output '\\1'

note the \' in the output is the standard python quotes for string output

the value of your variable is '\\1'


Below function will strip the empty spces and return the strings without quotes. If there are no quotes then it will return same string(stripped)

def removeQuote(str):
str = str.strip()
if re.search("^[\'\"].*[\'\"]$",str):
    str = str[1:-1]
    print("Removed Quotes",str)
else:
    print("Same String",str)
return str

참고URL : https://stackoverflow.com/questions/3085382/python-how-can-i-strip-first-and-last-double-quotes

반응형