Python中的“就地"字符串修改 [英] 'in-place' string modifications in Python

查看:30
本文介绍了Python中的“就地"字符串修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,字符串是不可变的.

In Python, strings are immutable.

逐个字符遍历字符串并修改它的标准习语是什么?

What is the standard idiom to walk through a string character-by-character and modify it?

我能想到的唯一方法是一些与连接结果字符串相关的非常糟糕的技巧.

The only methods I can think of are some genuinely stanky hacks related to joining against a result string.

--

在 C:

for(int i = 0; i < strlen(s); i++)
{
   s[i] = F(s[i]);
}

这是超级表现力,准确地说明了我在做什么.这就是我正在寻找的.

This is super expressive and says exactly what I am doing. That is what I am looking for.

推荐答案

不要使用字符串,使用像 bytearray 这样可变的东西:

Don't use a string, use something mutable like bytearray:

#!/usr/bin/python

s = bytearray("my dog has fleas")
for n in xrange(len(s)):
    s[n] = chr(s[n]).upper()
print s

结果:

MY DOG HAS FLEAS

因为这是一个 bytearray,所以您不必(必然)使用 字符.您正在使用字节.所以这也有效:

Since this is a bytearray, you aren't (necessarily) working with characters. You're working with bytes. So this works too:

s = bytearray("\x81\x82\x83")
for n in xrange(len(s)):
    s[n] = s[n] + 1
print repr(s)

给出:

bytearray(b'\x82\x83\x84')

如果您想修改 Unicode 字符串中的字符,您可能需要使用 memoryview,虽然它不直接支持 Unicode.

If you want to modify characters in a Unicode string, you'd maybe want to work with memoryview, though that doesn't support Unicode directly.

这篇关于Python中的“就地"字符串修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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