在python字符串中插入连字符

Jon*_*Lee 0 python string hyperlink hyphen

我正在抓一个列表,但想将字符串转换为永久链接,每个单词之间都有连字符.

例如,我有一个列表:

['hi there', 'help please','with my problem']
Run Code Online (Sandbox Code Playgroud)

我希望它最终像:

['hi-there','help-please', 'with-my-problem']
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

mgi*_*son 6

如果你只关心用单个连字符替换单个空格,那么其他答案工作得很好(特别是@ kindall's,这也确保你不会得到前导或尾随连字符).但是,如果要转换"foo bar""foo-bar",他们就会失败.

怎么样:

def replace_runs_of_whitespace_with_hyphen(word):
    return '-'.join(word.split())

hyphrases = [replace_runs_of_whitespace_with_hyphen(w) for w in phrases]
Run Code Online (Sandbox Code Playgroud)

或者使用正则表达式(但这可能导致前导/尾随连字符):

import re
re.sub(r'\s+', '-', word)
Run Code Online (Sandbox Code Playgroud)