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.
-
1Python 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.Aaron D– Aaron D2015年01月15日 14:36:05 +00:00Commented Jan 15, 2015 at 14:36
4 Answers 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.
3 Comments
buffer? I know it has memoryview, but I don't think that works on str objects.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.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
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
FYI : You don't need to declare any variable, you can do the operations on the string directly
"Hello world"[2:] # llo world