It gives the character that is represented by the ASCII code "34".

If you look up an ASCII table you will notice that 34 = "

Answer from Loocid on Stack Overflow
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ calling-c-functions-from-python
Calling C Functions from Python | DigitalOcean
Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
Discussions

How to use the -c flag in python - Stack Overflow
I noticed in the python doc that there is a -c flag. Here is what python doc says: Execute the Python code in command. command can be one or more statements separated by newlines, with signific... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Can we use C code in Python? - Stack Overflow
I know that Python provides an API so you can call Python interpreter in C code, but what I want is the opposite. My program needs to use some C API, so the code must be written in C. But I also w... More on stackoverflow.com
๐ŸŒ stackoverflow.com
printf - How to print a C format in python - Stack Overflow
A python newbie question: I would like to print in python with the c format with a list of parameters: agrs = [1,2,3,"hello"] string = "This is a test %d, %d, %d, %s" How can I print using python... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How is python able to use c code?
There is an API in the C that you can use to interact with Python objects from C code, which is the same API that python uses internally to bootstrap itself in many cases. There are good guides in the official python docs for how to make a python module in C in detail, but the overview of how it's done is: Create a c source file Include the Python.h header file, which exists on any system with the python interpreter installed. There are functions and macros in the Python.h header that allow you to create a python module "object", which can be imported, and to specify which functions should be part of that object, and for each function, you can specify it's python function signature, although from a C perspective, all the values passed into a python function are just python objects (pointers to a PyObject struct) The PyObject structure is the fundamental data type inside the python interpreter. It is a polymorphic struct, which is really neat. You can implement polymorphism and object orientation inside of C with some neat struct casting tricks, and that's what python does. Therefore, there are macros to convert the PyObject struct coming into your function to a PyListObject struct, for example, and then there are more C APIs for doing what you need to do to a list (append, insert, delete, etc.) Now, once your C code is all written up, you need to compile it. This would be tricky, except that python's setuptools (setup.py) has utilities for including C extensions in your library. So, you can just compile it through that tool while mostly ignoring the complexity of compiling and linking manually. At the end of the day, if you created a module named foo in C, you should be able to simply import and use it like any other python module. For example, the csv module is implemented entirely in C, although you'd probably never know it! More on reddit.com
๐ŸŒ r/learnpython
11
6
September 18, 2021
๐ŸŒ
Rose-Hulman Institute of Technology
rose-hulman.edu โ€บ class โ€บ cs โ€บ csse120 โ€บ Resources โ€บ C โ€บ Python_vs_C.html
Python and C -- Comparisons and Contrasts
It is a work in progress.We welcome comments or suggestions (especially suggestions for additional entries) from students ยท # Simple Python program year = 2007 print "Hello World!" print "CSSE 120 changed a lot in %d." % (year)}
๐ŸŒ
DEV Community
dev.to โ€บ erikwhiting88 โ€บ how-to-use-c-functions-in-python-7do
How to Use C Functions in Python - DEV Community
August 4, 2019 - So basically, any time we want to use that C function within Python, we call the factorial function which will run the C function with the parameter passed in by the user and evaluate the result.
๐ŸŒ
Medium
medium.com โ€บ nabla-squared โ€บ how-to-use-c-code-in-python-582491e572d1
How to use C code in Python. โ€ฆ and should we do this? | by Dorian Lazar | Nabla Squared | Medium
May 31, 2021 - If all you want is just to speed up your Python program, then there is actually an easier way rather than writing certain parts of your program in C. You can just use PyPy instead of Python when executing your app. PyPy is an alternative implementation of the Python programming language which uses just-in-time compilation to speed up the same python code with little or no changes to your code.
๐ŸŒ
Real Python
realpython.com โ€บ c-for-python-programmers
C for Python Programmers โ€“ Real Python
March 18, 2026 - Browse Topics Guided Learning Paths Basics Intermediate Advanced ยท ai algorithms api best-practices career community databases data-science data-structures data-viz devops django docker editors flask front-end gamedev gui machine-learning news numpy projects python stdlib testing tools web-dev web-scraping ... The purpose of this tutorial is to get an experienced Python programmer up to speed with the basics of the C language and how itโ€™s used in the CPython source code.
Find elsewhere
๐ŸŒ
Real Python
realpython.com โ€บ build-python-c-extension-module
Building a Python C Extension Module โ€“ Real Python
March 18, 2026 - Still, there may be other lesser-used system calls that are only accessible through C. The os module in Python is one example. This is not an exhaustive list, but it gives you the gist of what can be done when extending Python using C or any other language. To write Python modules in C, youโ€™ll need to use the Python API, which defines the various functions, macros, and variables that allow the Python interpreter to call your C code.
๐ŸŒ
Python Tips
book.pythontips.com โ€บ en โ€บ latest โ€บ python_c_extension.html
22. Python C extensions โ€” Python Tips 0.1 documentation
An interesting feature offered to developers by the CPython implementation is the ease of interfacing C code to Python. There are three key methods developers use to call C functions from their python code - ctypes, SWIG and Python/C API.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ using-c-codes-in-python-set-1
Using C codes in Python | Set 1 | GeeksforGeeks
March 18, 2019 - Prerequisite: How to Call a C function in Python Let's discuss the problem of accessing C code from Python. As it is very evident that many of Pythonโ€™s built-in libraries are written in C. So, to access C is a very important part of making Python talk to existing libraries.
Top answer
1 of 2
128

I want to invoke those C function or executables in python. Is that possible.

Yes, you can write C code that can be imported into Python as a module. Python calls these extension modules. You can invoke it from Python directly, an example from the documentation:

Python Code

import example
result = example.do_something()

C Code

static PyObject * example(PyObject *self)
{
    // do something
    return Py_BuildValue("i", result);
}

If I want the C code to be a library, which means I use it with #include and linkage of the *.o likely in python, how to do it or is that possible.

You build it as a shared library *.dll or *.so You can also investigate using distutils to distribute your module.

If I write the C code into executable, which means it becomes a command, can I invoke it in python directly?

If you write a *.exe then you are doing the opposite (invoking Python from C). The method you choose (exe vs shared library) depends on if you want a "C program with some Python" or a "Python program with some C".

Also, I heard that python code can be compiled, does that mean we can execute the code without the source file? Are the output files binary files? Does it improve performance?

Python reads *.py files and compiles to *.pyc bytecode files when you run it. The bytecode is then run in the Python virtual machine. This means "executing the same file is faster the second time as recompilation from source to bytecode can be avoided." (from the Python glossary) So if you haven't edited your *.py files, it will run the *.pyc. You can distribute *.pyc files without *.py files, however they are not encrypted and can be reverse-engineered.

2 of 2
16

You don't necessary need to extend Python (which is not trivial, btw), but can use foreign function interface such as ctypes.

๐ŸŒ
University of Toronto
cs.toronto.edu โ€บ ~patitsas โ€บ cs190 โ€บ c_for_python.html
C for Python Programmers
We'll start with several general principles, working toward a complete โ€” but limited โ€” C program by the end of Section 1. One major difference between C and Python is simply how you go about executing programs written in the two languages. With C programs, you usually use a compiler when ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how is python able to use c code?
r/learnpython on Reddit: How is python able to use c code?
September 18, 2021 -

I was always curious how python modules in c work. I know how to write and use a python c module, but i dont know how it works internally. Can anyone put me in the right path where can i start, an article or sthm or try to explain. And are there any simple tutorials to implement that sort of thing. Like calling .so files from your language etc...

Top answer
1 of 1
3
There is an API in the C that you can use to interact with Python objects from C code, which is the same API that python uses internally to bootstrap itself in many cases. There are good guides in the official python docs for how to make a python module in C in detail, but the overview of how it's done is: Create a c source file Include the Python.h header file, which exists on any system with the python interpreter installed. There are functions and macros in the Python.h header that allow you to create a python module "object", which can be imported, and to specify which functions should be part of that object, and for each function, you can specify it's python function signature, although from a C perspective, all the values passed into a python function are just python objects (pointers to a PyObject struct) The PyObject structure is the fundamental data type inside the python interpreter. It is a polymorphic struct, which is really neat. You can implement polymorphism and object orientation inside of C with some neat struct casting tricks, and that's what python does. Therefore, there are macros to convert the PyObject struct coming into your function to a PyListObject struct, for example, and then there are more C APIs for doing what you need to do to a list (append, insert, delete, etc.) Now, once your C code is all written up, you need to compile it. This would be tricky, except that python's setuptools (setup.py) has utilities for including C extensions in your library. So, you can just compile it through that tool while mostly ignoring the complexity of compiling and linking manually. At the end of the day, if you created a module named foo in C, you should be able to simply import and use it like any other python module. For example, the csv module is implemented entirely in C, although you'd probably never know it!
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_further_extensions.htm
Python - Further Extensions
Once you install your extensions, you would be able to import and call that extension in your Python script as follows โˆ’ ... Hello, Python extensions!! As you will most likely want to define functions that accept arguments, you can use one of the other signatures for your C functions.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ extending โ€บ extending.html
1. Extending Python with C or C++ โ€” Python 3.14.7 documentation
In many cases, it is possible to avoid writing C extensions and preserve portability to other implementations. For example, if your use case is calling C library functions or system calls, you should consider using the ctypes module or the cffi library rather than writing custom C code.
๐ŸŒ
Readthedocs
reptate.readthedocs.io โ€บ developers โ€บ python_c_interface.html
Tutorial: Interfacing Python and C code โ€” RepTate 1.4.0 documentation
The only work we need to do to integrate C code in Python is on Pythonโ€™s side. The steps for interfacing Python with C using Ctypes. are: ... As an example of C function, we write a simple function that takes as input an array of double and return the square. It is evident that such a simple function (that calculates the square of an array) does not justify the use of C, but it is a good place to start.
Top answer
1 of 3
3

It's combining two-arg next (which pulls the next value from an iterator, and if the iterator is exhausted returns the second argument as the default) with a generator expression, which is like a lazy list comprehension (it produces an iterator/generator that produces values on demand).

So:

r = next((c for c in l if config.equalsForConfigSet(c)), None)

in English, means "Get the first element of l for which config.equalsForConfigSet of that element is truthy; if no such element is found, return None". And it does it lazily, or if you prefer, with short-circuiting, so as soon as one c value passes, it doesn't need to continue; the rest of l isn't even loaded, let alone tested (unlike how a list comprehension would do it).

In code, you could express the same behavior with a function like so:

def firstEqualsConfigSet(l, config):
    for c in l:
        if config.equalsForConfigSet(c):
            # Short-circuit: got one hit, return it
            return c
    # Didn't find anything
    return None  # Redundant to explicitly return None, but illustrating
                 # that two-arg next could use non-None default

then use the function to do:

r = firstEqualsConfigSet(l, config)
2 of 3
2

My understanding is

next(iterator, default) The next() function returns the next item from the iterator.

its taking 'c' from the for loop which is extracting c from the list l (populated earlier), wherein the for loop is evaluating with a condition that config.equalsForConfigSet(C) should return true.

If there is no value for 'c' in the first parameter to next(), it will return None

https://www.programiz.com/python-programming/methods/built-in/next

Top answer
1 of 3
5

Some ways would be:

def mod_c0(a, b):
    if b < 0:
        b = -b
    return -1 * (-a % b) if a < 0 else a % b
def mod_c1(a, b):
    return (-1 if a < 0 else 1) * ((a if a > 0 else -a) % (b if b > 0 else -b))
def mod_c2(a, b):
    return (-1 if a < 0 else 1) * (abs(a) % abs(b))
def mod_c3(a, b):
    r = a % b
    return (r - b) if (a < 0) != (b < 0) and r != 0 else r
def mod_c4(a, b):
    r = a % b
    return (r - b) if (a * b < 0) and r != 0 else r
def mod_c5(a, b):
    return a % (-b if a ^ b < 0 else b)
def mod_c6(a, b):
    a_xor_b = a ^ b
    n = a_xor_b.bit_length()
    x = a_xor_b >> n
    return a % (b * (x | 1))
def mod_c7(a, b):
    a_xor_b = a ^ b
    n = a_xor_b.bit_length()
    x = a_xor_b >> n
    return a % ((-b & x) | (b & ~x))
def mod_c8(a, b):
    q, r = divmod(a, b)
    if (a >= 0) != (b >= 0) and r:
        q += 1
    return a - q * b
def mod_c9(a, b):
    if a >= 0:
        if b >= 0:
            return a % b
        else:
            return a % -b
    else:
        if b >= 0:
            return -(-a % b)
        else:
            return a % b

which all work as expected, e.g.:

print(mod_c0(31, -3))
# 1

Essentially, mod_c0() implements an optimized version of mod_c1() and mod_c2(), which are identical except that in mod_c1() the call to (relatively expensive) call to abs() is replaced by a ternary conditional operator with the same semantic. Instead, mod_c3() and mod_c4() try to directly fix the a % b value for the cases where it is needed. The difference between the two is in how they detect opposite signs of the arguments: (a < 0) != (b != 0) versus a * b < 0. The mod_c5() approach is inspired by @ArborealAnole's answer, and essentially uses the bit-wise xor to handle the cases correctly, while mod_c6() and mod_c7() are the same as @ArborealAnole's answer but using adaptive right shift with int.bit_length(). The mod_c8() approach uses a corrected definition of integer division to fix up the modulus value. The mod_c9() method is inspired by @NeverGoodEnough's answer, and essentially goes full conditional.


Covering all sign cases:

vals = (3, -3, 31, -31)
s = '{:<{n}}' * 4
n = 14
print(s.format('a', 'b', 'mod(a, b)', 'mod_c(a, b)', n=n))
print(s.format(*(('-' * (n - 1),) * 4), n=n))
for a, b in itertools.product(vals, repeat=2):
    print(s.format(a, b, mod(a, b), mod_c0(a, b), n=n))
a             b             mod(a, b)     mod_c(a, b)   
------------- ------------- ------------- ------------- 
3             3             0             0             
3             -3            0             0             
3             31            3             3             
3             -31           -28           3             
-3            3             0             0             
-3            -3            0             0             
-3            31            28            -3            
-3            -31           -3            -3            
31            3             1             1             
31            -3            -2            1             
31            31            0             0             
31            -31           0             0             
-31           3             2             -1            
-31           -3            -1            -1            
-31           31            0             0             
-31           -31           0             0             

A bit more tests and benchmarks:

import itertools


n = 100
l = [x for x in range(-n, n + 1)]
ll = [(a, b) for a, b in itertools.product(l, repeat=2) if b]


funcs = mod_c0, mod_c1, mod_c2, mod_c3, mod_c4, mod_c5, mod_c6, mod_c7, mod_c8, mod_c9
for func in funcs:
    correct = all(func(a, b) == funcs0 for a, b in ll)
    print(f"{func.__name__}  correct:{correct}  ", end="")
    %timeit -n 8 -r 8 [func(a, b) for a, b in ll]
# mod_c0  correct:True  8 loops, best of 8: 9.67 ms per loop
# mod_c1  correct:True  8 loops, best of 8: 11.1 ms per loop
# mod_c2  correct:True  8 loops, best of 8: 12.3 ms per loop
# mod_c3  correct:True  8 loops, best of 8: 10.3 ms per loop
# mod_c4  correct:True  8 loops, best of 8: 10 ms per loop
# mod_c5  correct:True  8 loops, best of 8: 10.1 ms per loop
# mod_c6  correct:True  8 loops, best of 8: 17.1 ms per loop
# mod_c7  correct:True  8 loops, best of 8: 20.3 ms per loop
# mod_c8  correct:True  8 loops, best of 8: 15.8 ms per loop
# mod_c9  correct:True  8 loops, best of 8: 9.29 ms per loop

Perhaps there are better (shorter?, faster?) ways, given that the implementation of Python's % using C's % seems much simpler:

((a % b) + b) % b

To get some feeling on how the C-style % computation (mod_c*() functions from above) stands against the usual % or the operations required to get Python-style % from C:

def mod_py(a, b):
    return a % b

def mod_c2py(a, b):
    return ((a % b) + b) % b


%timeit [mod_py(a, b) for a, b in ll]
# 100 loops, best of 3: 5.85 ms per loop
%timeit [mod_c2py(a, b) for a, b in ll]
# 100 loops, best of 3: 7.84 ms per loop

Note of course that mod_c2py() is only useful to get a feeling of what performances we could expect from a mod_c() function.


(EDITED to fix some of the proposed methods and include some timings)

(EDITED-2 to add the mod_c5() solution)

(EDITED-3 to add the mod_c6() to mod_c9() solutions)

2 of 3
3

I am following up the very comprehensive answer of @norok2. I have tried the super-naive approach with branches, and it appears to be slightly but consistently faster (~2-4%).

def mod_naive(x,y):
  if y < 0:
    if x < 0:
      return x%y
    else:
      return (x%-y)
  else:
    if x < 0:
      return -(-x%y)
    else:
      return x%y

or with a lambda (does not affect speed, only coolness):

mod_naive = lambda x,y: (x%y if x < 0 else x%-y) if y < 0 else (-(-x%y) if x < 0 else x%y)

Compared to @norok2's fastest solution (mod_c0):

mod_c0 correct: True
100 loops, best of 3: 6.86 ms per loop

mod_naive correct: True
100 loops, best of 3: 6.58 ms per loop

My (naive) guess on the reason why is that the branch prediction algorithms will eventually produce less operations overall.

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-call-a-c-function-in-python
How to Call a C Function in Python
July 20, 2023 - The Python ctypes library is a robust resource that empowers us to generate C-compatible data types and directly invoke functions in dynamic link libraries or shared libraries using Python. First, let's create a simple C function to demonstrate the process ? // save as math_operations.c #include <stdio.h> int add(int a, int b) { return a + b; } int multiply(int a, int b) { return a * b; } ... import ctypes import os # For demonstration, we'll simulate having the library # In practice, you would load your actual shared library: # lib = ctypes.CDLL('./math_operations.so') # For this demo, we'll use the built-in math library lib = ctypes.CDLL(None) # Load current process symbols # Let's demonstrate with a simple example print("ctypes library loaded successfully")