sách gpt4 ăn đã đi

python - Python中的“就地”字符串修改

In lại Tác giả: IT Lão Cao 更新时间:2023-10-28 20:49:27 30 4
mua khóa gpt4 giày nike

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

逐个字符遍历字符串并对其进行修改的标准习语是什么?

我能想到的唯一方法是一些与加入结果字符串相关的真正臭名昭著的黑客攻击。

--

在 C 中:

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

Đây là siêu 表达力,并准确地说明了我在做什么。这就是我要找的。

câu trả lời hay nhất

不要使用字符串,使用可变的东西,比如 bytearray:

#!/usr/bin/python

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

kết quả:

MY DOG HAS FLEAS

biên tập:

由于这是一个 bytearray,您不必(必然)使用 characters。您正在使用 byte。所以这也有效:

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。

关于python - Python中的“就地”字符串修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3463746/

30 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress