python - 将列表中的每个项目的空格替换为破折号-python

标签 python whitespace replace

有没有一种方法可以简化这个循环,我用破折号替换列表中每个项目的空格?

for item in a_list:
    alist[alist.index(item)] = '-'.join(item.split(" "))

还是这样更好?

for item in a_list:
    alist[alist.index(item)] = item.replace(" ", "-")

注意:上述解决方案仅更新此列表中的第一个匹配项,正如 David 所建议的那样,使用列表理解 来完成上述任务。

我有一个单词列表,有些有破折号,有些没有。 a_list 中的项目如下所示:

this-item has a-dash
this has dashes
this should-have-more dashes
this foo
doesnt bar
foo
bar

输出应该是这样的,其中列表中的所有项目都应该有破折号而不是空格:

this-item-has-a-dash
this-has-dashes
this-should-have-more-dashes
this-foo
doesnt-bar
foo
bar

最佳答案

使用列表理解:

a_list = [e.replace(" ", "-") for e in a_list]

关于python - 将列表中的每个项目的空格替换为破折号-python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486598/

相关文章:

python - 为什么 pikepdf 在使用 Acrobat DC 创建的 PDF 上填充某些 PDF 字段而不填充其他字段

html - 使用 100% 宽度时的空白

c - C 表达式中忽略空格的规则

xslt - XSL 输出方法文本,包括 xsl 中的空格

python - s3multiput (boto) 从 EC2 实例上传到 s3 的静默失败

python - Ansible跳过无法访问的主机

python - Pip3 不适用于 OS X

html - 如何仅使用 CSS 鼠标相关事件来换出文本框中的文本?

java - 删除除连字符之外的所有特殊字符

c# - 使用 Regex.Replace 保留可以变化的字符