更改字符串中的一个字符 [英] Changing one character in a string

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

问题描述

Python 中替换字符串中字符的最简单方法是什么?

例如:

text = "abcdefg";文本[1] = "Z";^

解决方案

不要修改字符串.

以列表的形式使用它们;仅在需要时将它们转换为字符串.

<预><代码>>>>s = list("你好 zorld")>>>秒['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']>>>s[6] = 'W'>>>秒['你好,世界']>>>"".join(s)'你好,世界'

Python 字符串是不可变的(即它们不能被修改).这有很多的原因.使用列表直到你别无选择,然后才将它们变成字符串.

What is the easiest way in Python to replace a character in a string?

For example:

text = "abcdefg";
text[1] = "Z";
           ^

解决方案

Don't modify strings.

Work with them as lists; turn them into strings only when needed.

>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'

Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.

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

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