How to cut off question mark in url with functions.php

Try this, which uses the parse_request hook: (you can add other conditions, e.g. check whether $wp->query_vars['name'] is not empty, if you want to)

add_action( 'parse_request', 'wpse_400900_parse_request', 1 );
function wpse_400900_parse_request( $wp ) {
    // Redirect if the URL ends with a ? like https://example.com?
    if ( ! empty( $_SERVER['REQUEST_URI'] ) &&
        ltrim( $_SERVER['REQUEST_URI'], "https://wordpress.stackexchange.com/" ) === "{$wp->request}?"
    ) {
        wp_redirect( home_url( $wp->request ) );
        exit;
    }
}