Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operations with strings in python

Tags:

python

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.

like image 461
Gleb Makarchuk Avatar asked Jun 08 '26 14:06

Gleb Makarchuk


1 Answers

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.

like image 155
Ignacio Vazquez-Abrams Avatar answered Jun 10 '26 02:06

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!