简体   繁体   中英

'C-style' strings in Python

A very popular question is how to reverse a C-Style string. The C-Style string by definition is a string that is terminated by a null('\\0'). Using C(or maybe C++), it is possible to use pointers to manipulate the string to reverse its contents in-place.

If somebody asks the question, "How do you reverse a C-style string in Python?", what would some of the possible answers be?

Thanks

If you need to "reverse a C-style string in Python", I think the end result must also be a c-style string.

That is how I would understand the question, but the above answers do not support this.

See the interactive session below:

>>> 
>>> original = "abc\0"
>>> finish_correct = "cba\0"
>>> original
'abc\x00'
>>> finish_correct
'cba\x00'
>>> 
>>> answer = original[:-1]  # remove final null
>>> answer = answer[::-1]  # reverse string
>>> # Extended slice syntax:  [begin:end:step]
>>> # So, [::-1] means take whole string, but in reverse.
>>> answer
'cba'
>>> answer = answer + "\0"
>>> answer
'cba\x00'
>>> answer == finish_correct
True

Also note, Python strings are immutable. This means that they can never be changed. You can make new strings that are assigned to the same variable name, but the in-memory image for a given strings will never change. Thus, the notion of "reverse a string in place" can not happen in Python.

Hope this helps. If so, please up-vote and accept the answer. Thanks. :-)

Python doesn't use C-style strings; Python strings can contain an embedded NUL, so C-style strings are not used, but rather an explicit length.

>>> 'abc\0def'[::-1]
'fed\x00cba'

Since C doesn't have a string type, it represents character strings as pointers to char , where the last byte (assuming ASCII, not wide-characters) is \\0 . It's a representation . By the way, this default implementation has the deficiency that \\0 can't be part of such a string. If that's needed, a different representation is required (such as representing a string as a pointer + a length integer).

Python, OTOH has a string type, and it's opaque to the user how this type is represented. Therefore, a "C-style string" is a meaningless concept in Python.

Python strings are immutable . You could emulate a C-style string with a table of chars, but I don't see why you would bother.

But if you did have a C-style "string" (ie table of characters), then all you'd need to do is swap s[i] with s[len(s)-i-1]:

for i in range(0, len(a) - 2):
    a[i], a[len(a) - 1 - i] = a[len(a) - 1 - i], a[i]

(if a is your C-style string)

Note how you don't need a temporary variable(granted you don't need one in C either, considering how you could use the null character as a temp space).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM