在python字符串中插入连字符

2024-06-28 19:04:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在抓取一个列表,但希望将字符串转换为permalinks,每个单词之间都有连字符。

例如,我有一个列表:

['hi there', 'help please','with my problem']

我希望它的结局是:

['hi-there','help-please', 'with-my-problem']

最好的方法是什么?


Tags: 方法字符串列表mywithhelphi字符
3条回答
phrases   = ['hi there', 'help please','with my problem']
hyphrases = [p.strip().replace(" ", "-") for p in phrases]
>>> spaces = ['hi there', 'help please','with my problem']
>>> hyphens = [s.replace(' ','-') for s in spaces]
>>> print hyphens
['hi-there','help-please', 'with-my-problem']

如果你只关心用一个连字符替换一个空格,那么其他的答案就很好了(尤其是@kindall,它也确保你不会以前导或尾随连字符结束)。但是,如果要将"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]

或者使用regex(但这一个可能导致前导/尾随连字符):

import re
re.sub(r'\s+', '-', word)

相关问题 更多 >