[python] 공백을 밑줄로 바꾸려면 어떻게해야합니까?

멋진 URL을 만들기 위해 문자열에서 공백을 밑줄로 바꾸고 싶습니다. 예를 들어 :

"This should be connected" becomes "This_should_be_connected" 

Django와 함께 Python을 사용하고 있습니다. 정규식을 사용하여이 문제를 해결할 수 있습니까?



답변

정규식이 필요하지 않습니다. 파이썬에는 필요한 것을 수행하는 내장 문자열 메소드가 있습니다.

mystring.replace(" ", "_")


답변

공백을 바꾸는 것은 좋지만 물음표, 아포스트로피, 느낌표 등과 같은 다른 URL 적대적 문자를 처리하는 것이 좋습니다.

또한 SEO 전문가들 사이의 일반적인 합의 는 URL에서 밑줄보다 대시가 선호된다는 것입니다.

import re

def urlify(s):

    # Remove all non-word characters (everything except numbers and letters)
    s = re.sub(r"[^\w\s]", '', s)

    # Replace all runs of whitespace with a single dash
    s = re.sub(r"\s+", '-', s)

    return s

# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))


답변

Django는이를 수행하는 ‘slugify’기능과 다른 URL 친화적 인 최적화 기능을 가지고 있습니다. 기본 필터 모듈에 숨겨져 있습니다.

>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")

this-should-be-connected

이것은 정확히 요청한 결과는 아니지만 IMO는 URL에 사용하는 것이 좋습니다.


답변

이것은 공백 이외의 공백 문자를 고려하며 re모듈을 사용하는 것보다 빠릅니다 .

url = "_".join( title.split() )


답변

re모듈 사용 :

import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And     so\tshould this')  # And_so_should_this

위와 같이 여러 공간이나 다른 여백 가능성이 없다면 string.replace다른 사람들이 제안한대로 사용 하는 것이 좋습니다.


답변

문자열의 replace 메소드를 사용하십시오.

"this should be connected".replace(" ", "_")

"this_should_be_disconnected".replace("_", " ")


답변

놀랍게도이 라이브러리는 아직 언급되지 않았습니다

python-slugify라는 python 패키지는 꽤 훌륭하게 처리합니다.

pip install python-slugify

다음과 같이 작동합니다.

from slugify import slugify

txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")

txt = 'Nín hǎo. Wǒ shì zhōng guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")

txt = 'Компьютер'
r = slugify(txt)
self.assertEquals(r, "kompiuter")

txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a")