在字符串中的每个字符前后放置一个符号 [英] Put a symbol before and after each character in a string

查看:52
本文介绍了在字符串中的每个字符前后放置一个符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为字符串中的每个字符添加括号.所以

HelloWorld"

应该变成:

"[H][e][l][l][o][W][o][r][l][d]"

我用过这个代码:

word = "HelloWorld"新词 = ""单词中的字母:newWord += "[%s]" % 字母

这是最直接的方法,但字符串连接非常慢.有关加速此代码的任何建议.

解决方案

>>>s = "你好世界">>>''.join('[{}]'.format(x) for x in s)'[你好,世界]'

如果字符串很大,那么使用 str.join 和列表解析将比使用生成器表达式更快且内存效率更高(https://stackoverflow.com/a/9061024/846892):

<预><代码>>>>''.join(['[{}]'.format(x) for x in s])'[你好,世界]'

<小时>

来自 Python 性能提示:

避免这种情况:

s = ""对于列表中的子字符串:s += 子串

使用 s = "".join(list) 代替.前者是构建大字符串时非常常见的灾难性错误.

I would like to add brackets to each character in a string. So

"HelloWorld"

should become:

"[H][e][l][l][o][W][o][r][l][d]"

I have used this code:

word = "HelloWorld"
newWord = ""
for letter in word:
    newWord += "[%s]" % letter

which is the most straightforward way to do it but the string concatenations are pretty slow. Any suggestions on speeding up this code.

解决方案

>>> s = "HelloWorld"
>>> ''.join('[{}]'.format(x) for x in s)
'[H][e][l][l][o][W][o][r][l][d]'

If string is huge then using str.join with a list comprehension will be faster and memory efficient than using a generator expression(https://stackoverflow.com/a/9061024/846892):

>>> ''.join(['[{}]'.format(x) for x in s])
'[H][e][l][l][o][W][o][r][l][d]'


From Python performance tips:

Avoid this:

s = ""
for substring in list:
    s += substring

Use s = "".join(list) instead. The former is a very common and catastrophic mistake when building large strings.

这篇关于在字符串中的每个字符前后放置一个符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆