Skip to content

Instantly share code, notes, and snippets.

@sergiobuj
Last active May 15, 2024 11:57
Show Gist options
  • Save sergiobuj/fbe371d89197a9bcf0a3a02fdadd6366 to your computer and use it in GitHub Desktop.
Save sergiobuj/fbe371d89197a9bcf0a3a02fdadd6366 to your computer and use it in GitHub Desktop.
How to align numbers to words of a sentence in the next line?
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 14,
"id": "b90fb1a3-29a7-498d-8070-2296410ef5d3",
"metadata": {},
"outputs": [],
"source": [
"def count_letters(word):\n",
" chars = map(lambda x: 1 if x.isalpha() else 0, word)\n",
" return sum(chars)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "31a93bdb-3991-4267-82f7-e7ef4f415959",
"metadata": {},
"outputs": [],
"source": [
"text = \"How to align numbers to words of a sentence in the next line?\"\n",
"\n",
"lengths = list(map(count_letters, text.split()))\n",
"alignments = \" \".join(map(lambda x: f\"{x:<{x}}\", lengths))"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "bba48c42-3b22-4561-8078-e67ceddc59e7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"How to align numbers to words of a sentence in the next line?\n",
"3 2 5 7 2 5 2 1 8 2 3 4 4 \n"
]
}
],
"source": [
"print(text)\n",
"print(alignments)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ab613dc1-f3b0-41b2-8e91-7bcacae5d11a",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment