我正在抓一个列表,但想将字符串转换为永久链接,每个字之间都有连字符。
例如,我有一个列表:
['hi there', 'help please','with my problem']
我希望它最终成像:
['hi-there','help-please', 'with-my-problem']
最好的方法是什么?
答案 0 :(得分:5)
如果您只关心用单个连字符替换单个空格,那么其他答案效果很好(特别是@ 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]
或者使用正则表达式(但这可能导致前导/尾随连字符):
import re
re.sub(r'\s+', '-', word)
答案 1 :(得分:3)
>>> spaces = ['hi there', 'help please','with my problem']
>>> hyphens = [s.replace(' ','-') for s in spaces]
>>> print hyphens
['hi-there','help-please', 'with-my-problem']
答案 2 :(得分:2)
phrases = ['hi there', 'help please','with my problem']
hyphrases = [p.strip().replace(" ", "-") for p in phrases]
答案 3 :(得分:0)
您可以使用:
wordlist = ['hi there', 'help please', 'with my problem']
hyphenated_wordlist = map(lambda s: s.replace(' ', '-'), wordlist)