在Python中的某个位置添加字符串 [英] Add string in a certain position in Python

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

问题描述

Python 中是否有任何函数可用于在字符串的特定位置插入值?

像这样:

"3655879ACB6" 然后在位置 4 添加 "-" 成为 "3655-879ACB6"

解决方案

没有.Python 字符串是不可变的.

<预><代码>>>>s='355879ACB6'>>>s[4:4] = '-'回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:str"对象不支持项目分配

但是,可以创建一个包含插入字符的新字符串:

<预><代码>>>>s[:4] + '-' + s[4:]'3558-79ACB6'

Is there any function in Python that I can use to insert a value in a certain position of a string?

Something like this:

"3655879ACB6" then in position 4 add "-" to become "3655-879ACB6"

解决方案

No. Python Strings are immutable.

>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

It is, however, possible to create a new string that has the inserted character:

>>> s[:4] + '-' + s[4:]
'3558-79ACB6'

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

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