def select_captions(annotations, image_ids):
    """Select captions of given image_ids and return them with their image IDs.
    """

    # for fast lookup
    image_ids = set(image_ids)

    captions = []
    caption_image_ids = []

    for annotation in annotations:
        image_id = annotation['image_id']
        if image_id in image_ids:
            captions.append(annotation['caption'].replace('\n', ''))
            caption_image_ids.append(image_id)

    return captions, caption_image_ids