2

Currently I'm learning Python3, and I already have some experience with C. I need to shift string to get rid of two first bytes. Here's code in C:

char *a = "Hello World";
a += 2;
printf ("%s", a)

this program will output "llo World"

I was wondering if there is a way of doing such thing in Python efficiently, without copying the whole string.

1
  • 1
    Python isn't used to be efficient in the way you mean. The language has its own paradigm of 'Pythonic' code conventions, and using pointers to address memory spaces directly is not common. The answers to this question are all the standard "Pythonic" way to do things - treat the string as a list of characters and return a new list with the substring you want. Commented Jan 15, 2015 at 14:36

4 Answers 4

4

The closest operation in 2.x would be creating a buffer from the string and then slicing that. Creating the buffer is an additional operation, but only needs to be performed once since the buffer can be reused.

>>> a = 'Hello world'
>>> b = buffer(a)
>>> print b[2:]
llo world
>>> print b[:5]
Hello

3.x doesn't have buffer, but you shouldn't be trying to emulate the C code in Python regardless. Figure out what you're actually trying to do, and then write the appropriate Pythonic code for it.

Sign up to request clarification or add additional context in comments.

3 Comments

Does Python 3 have buffer? I know it has memoryview, but I don't think that works on str objects.
No, buffer is gone in 3.x. But you shouldn't be trying to emulate C in Python regardless, unless you want to write slower code.
OP did say he was using Python 3 though.
3

Python is higher level than C and understands what a string is. You can do:

s = "Hello World"
print(s[2:])

You can find more here: https://docs.python.org/3/tutorial/introduction.html#strings.

2 Comments

Slicing a string copies the elements.
Well, you can use a memoryview but it's probably not worth it in most cases and definitely not for a beginner.
2

Sure there is and is better than C

a = "Hello World"
print a[2:]

This is called slicing

Refer the image

enter image description here

3 Comments

and the third parameter for the increment in the slicing, meaning that with [::-1] you will get the list reversed
This does copy the sliced elements, unlike the C code.
i will remember that then, ok
0

FYI : You don't need to declare any variable, you can do the operations on the string directly

"Hello world"[2:] # llo world

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.