如何在Python中就地修改字符串?

WBOY
发布: 2023-08-20 18:53:16
转载
1725人浏览过

如何在python中就地修改字符串?

很不幸,您无法原地修改字符串,因为字符串是不可变的。只需从您想要收集的几个部分创建一个新的字符串。但是,如果您仍然需要一个能够原地修改Unicode数据的对象,您应该使用

  • io.StringIO对象
  • 数组模块

Let’s see what we discussed above −

返回一个包含缓冲区全部内容的字符串

Example

的中文翻译为:

示例

In this example, we will return a string with the entire contents of the buffer. We have a text stream StringIO −

import io

myStr = "Hello, How are you?"
print("String = ",myStr)

# StringIO is a text stream using an in-memory text buffer
strIO = io.StringIO(myStr)

# The getvalue() returns a string containing the entire contents of the buffer
print(strIO.getvalue())
登录后复制

Output

String = Hello, How are you?
Hello, How are you?
登录后复制

现在,让我们改变流的位置,写入新内容并显示

FashionLabs
FashionLabs

AI服装模特、商品图,可商用,低价提升销量神器

FashionLabs 38
查看详情 FashionLabs

立即学习Python免费学习笔记(深入)”;

Change the stream position and write new String

Example

的中文翻译为:

示例

We will see another example and change the stream position using the seek() method. A new string will be written at the same position using the write() method −

import io
myStr = "Hello, How are you?"

# StringIO is a text stream using an in-memory text buffer
strIO = io.StringIO(myStr)

# The getvalue() returns a string containing the entire contents of the buffer
print("String = ",strIO.getvalue())

# Change the stream position using seek()
strIO.seek(7)

# Write at the same position
strIO.write("How's life?")

# Returning the final string
print("Final String = ",strIO.getvalue())
登录后复制

Output

String = Hello, How are you?
Final String = Hello, How's life??
登录后复制

Create an array and convert it to Unicode string

Example

的中文翻译为:

示例

在这个例子中,使用array()创建一个数组,然后使用tounicode()方法将其转换为Unicode字符串 -

import array

# Create a String
myStr = "Hello, How are you?"

# Array
arr = array.array('u',myStr)
print(arr)

# Modifying the array
arr[0] = 'm'

# Displaying the array
print(arr)

# convert an array to a unicode string using tounicode
print(arr.tounicode())
登录后复制

Output

array('u', 'Hello, How are you?')
array('u', 'mello, How are you?')
mello, How are you?
登录后复制

以上就是如何在Python中就地修改字符串?的详细内容,更多请关注php中文网其它相关文章!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号