就地字符串反转 [英] in-place string reversal

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

问题描述

你如何反转字符串就地在python?我看到

围绕更高级别的数据结构有很多操作,而不是强调原始数据。我有点迷失,通过查看

a字符串对象周围的rev()或reverse()或strRev()函数,无法找到我的

方式。


我可以通过使用额外的内存从头到尾遍历:


strText =" foo"

strTemp =""

为strrxt中的chr:

strTemp = chr + strTemp

但是我该如何做到这一点?

算了吧!我得到了自己问题的答案。字符串是不可变的,

*甚至*在python中。为什么不! python编译器是用C语言编写的,对吗?

令人惊讶的是,写下你的问题可以给你一个

的解决方案。

PS :或者,如果我的假设字符串是不可变的并且就地可以反转
可能是错误的,请纠正我。

解决方案

并且额外记忆是指我上面给出的操作很贵,我相信。有没有一种有效的方法呢?


Sathyaish启发我们:

你将如何反转字符串in放置"在python?


你不会,因为字符串是不可变的。

算了吧!我得到了自己问题的答案。字符串是不可变的,*甚至*在python中。


确实:)

为什么不呢! python编译器是用C编写的,对吗?


是的。但是有什么关系呢?字符串在C中非常容易变化。

令人惊讶的是,写下你的问题可以给你一个解决方案。




:)


Sybren

-

世界的问题是愚蠢。并不是说应该对愚蠢的死刑进行处罚,但为什么我们不要仅仅拿掉

安全标签来解决问题呢? br />
Frank Zappa


Sathyaish写道:

并且说额外记忆我上面给出的操作很贵,我相信。有没有一种有效的方法呢?



如果我没记错,字符串是一个不可变列表。

我会这样做:

strTXT =" foo"
strREV = strTXT [:: - 1]
strREV



''of''


-

mph


How would you reverse a string "in place" in python? I am seeing that
there are a lot of operations around higher level data structures and
less emphasis on primitive data. I am a little lost and can''t find my
way through seeing a rev() or a reverse() or a strRev() function around
a string object.

I could traverse from end-to-beginning by using extra memory:

strText = "foo"
strTemp = ""
for chr in strText:
strTemp = chr + strTemp
but how would I do it in place?
Forget it! I got the answer to my own question. Strings are immutable,
*even* in python. Why not! The python compiler is written in C, right?
It is amazing how just writing down your problem can give you a
solution.
PS: Or, if my assumption that strings are immutable and an in-place
reversal is possible, is wrong, please correct me.

解决方案

And that the "extra-memory" operation I''ve given above is expensive, I
believe. Is there an efficient way to do it?


Sathyaish enlightened us with:

How would you reverse a string "in place" in python?
You wouldn''t, since strings are immutable.
Forget it! I got the answer to my own question. Strings are
immutable, *even* in python.
Indeed :)
Why not! The python compiler is written in C, right?
Yup. But what''s got that to do with it? Strings are very mutable in C.
It is amazing how just writing down your problem can give you a
solution.



:)

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don''t we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa


Sathyaish wrote:

And that the "extra-memory" operation I''ve given above is expensive, I
believe. Is there an efficient way to do it?


If i recall correctly a string is an immutable list.
I would do it this way:

strTXT = "foo"
strREV = strTXT[::-1]
strREV


''oof''

--
mph


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

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