Skip to content

Instantly share code, notes, and snippets.

@mkotsovoulou
Created March 20, 2022 13:22
Show Gist options
  • Save mkotsovoulou/f17c3793d249d72212fd135132b6d018 to your computer and use it in GitHub Desktop.
Save mkotsovoulou/f17c3793d249d72212fd135132b6d018 to your computer and use it in GitHub Desktop.
Strings in Python
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Strings\n",
"Declare a string variable named fruit and assing the value 'bananas'\n",
"Produce a formatted output with the fruit contents and how many characters exist in the string using the len function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fruit = 'bananas'\n",
"print(f\"{fruit} has {len(fruit)} characters\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Print the character in the first position in the fruit"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"letter = fruit[1]\n",
"print(letter)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Print the character in the zero (index) position in the string\n",
"Print the character in the fifth (index) position in the string"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"letter = fruit[0]\n",
"print(letter)\n",
"\n",
"letter = fruit[5]\n",
"print(letter)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Find the last character in a string, using the index of the length -1"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"last = fruit[len(fruit)-1]\n",
"print(last)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Strings are immutable. So changes are not allowed\n",
"fruit[0]='J' -> so this command will raise a Type Error"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fruit[0]='J'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To change a string, declare a new one with the required change. You can use slicing from the position 1 until the end..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"new_fruit = 'J'+ fruit[1:]\n",
"print(new_fruit)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some slicing examples:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# String slices\n",
"print(fruit[2:4])\n",
"\n",
"#The first 3 characters: from 0 to 2\n",
"print(fruit[:3])\n",
"\n",
"# from the 4th character to the end\n",
"print(fruit[3:])\n",
"\n",
"# If the first index is greater than or equal to the second the result is an empty string\n",
"print(fruit[3:3])\n",
"\n",
"print(fruit[:])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## String Traversal : \n",
"using a **For Loop**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Traversal through a string with a for loop\n",
"for char in fruit:\n",
" print(char)\n",
" #print(char, end = \" \")\n",
"\n",
"print(\"\\n-------------------------------\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"using a **While Loop**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Traversal through a string with a while loop\n",
"index = 0\n",
"while index < len(fruit):\n",
" char = fruit[index]\n",
" print(index, char)\n",
" index = index + 1\n",
"print(f\"The end index value is {index}\")\n",
"print(\"--------------------------------\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Searching in Strings\n",
"lets find if letter 'g' exists in bananas"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Searching\n",
"search_for_letter = 'g'\n",
"if search_for_letter in fruit:\n",
" print(f\"{fruit} contains letter {search_for_letter}\")\n",
"else:\n",
" print(f\"{fruit} does not contain letter '{search_for_letter}'\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Searching in order to count letters in a string, using a for loop"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#looping and counting\n",
"count = 0\n",
"for letter in fruit:\n",
" if letter == search_for_letter:\n",
" count = count + 1\n",
"\n",
"if count > 0:\n",
" print(f\"{fruit} contains letter '{search_for_letter}' {count} times\")\n",
"else:\n",
" print(f\"{fruit} does not contain letter '{search_for_letter}'\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Counting occurances using the count() function"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(f\"{fruit} contains letter '{search_for_letter}' {fruit.count(search_for_letter)} times\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comparing Strings\n",
"is BANANAS equal to bananas?\n",
"and what if we convert everything to lower case in order to compare?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#comparing strings\n",
"fruit = 'BANANAS'\n",
"samefruit = 'bananas'\n",
"\n",
"if fruit==samefruit:\n",
" print(\"IN EXACT COMPARISON:\", fruit,\" same as \", samefruit)\n",
"else:\n",
" print(\"IN EXACT COMPARISON:\", fruit,\" NOT SAME AS \", samefruit)\n",
"\n",
"if fruit.lower() == samefruit.lower():\n",
" print(\"IN A CONVERTED COMPARISON: \", fruit,\" same as \", samefruit)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# String Functions\n",
"- len()\n",
"- .strip()\n",
"- .upper()\n",
"- .lower()\n",
"- .title()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sentence = \" Strings are an example of Python objects. An OBJECT contains both data (the actual string itself) and methods \"\n",
"length = len(sentence)\n",
"print(\"Length Before stripping:\" , length)\n",
"\n",
"sentence = sentence.strip()\n",
"length = len(sentence)\n",
"print(\"Length After stripping:\" , length)\n",
"\n",
"print(sentence.upper())\n",
"print(sentence.lower())\n",
"print(sentence.title())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## String functions:\n",
"- .startswith() \n",
"- .find() \n",
"- .isdigit()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Does the sentence start with the word 'strings'\n",
"print(sentence.startswith(\"strings\"))\n",
"\n",
"#In the next example, the method lower is called and then we use startswith to\n",
"#see if the resulting lowercase string starts with \"strings\". As long as we are\n",
"#careful with the order, we can make multiple method calls in a single expression.\n",
"print(sentence.lower().startswith(\"strings\"))\n",
"\n",
"# what is the position (index) on the string \"an\" in the sentence?\n",
"print(sentence.find('an'))\n",
"\n",
"# does x variable contain only digits\n",
"x = \"100\"\n",
"print(x.isdigit())\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## .split() \n",
"to separate a string into parts"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sometext=\"this is a line of text\"\n",
"words=sometext.split()\n",
"print(words)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for word in words:\n",
" print(word)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## .join() \n",
"the first example will return a new string by **joining** all items in a list into a string, using the space \" \" as **separator/delimeter**.\n",
"The delimeter can be anything...\n",
"In the secode example the delimeter is a semicolon ;"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"alltogether = \" \".join(words)\n",
"print(alltogether)\n",
"alltogether = \";\".join(words)\n",
"print(alltogether)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## .replace()\n",
"replace will replce all instances of the first string in the parenthesis with the one in the second parenthesis... ie. all \"a\" with \"e\" and all \"p\" with \"bb\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fruit=\"apple\"\n",
"newfruit = fruit.replace(\"a\",\"e\").replace(\"p\",\"bb\")\n",
"print(newfruit)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Advanced Search\n",
"Find all positions of letter 'a' in the sentence..."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"index = 0\n",
"while index != -1:\n",
" index = sentence.find('a', index) #fisearch for the first occurance\n",
" if index >= 0: # if a is found index will be positive\n",
" print(\" 'a' found in position \" , index) # display message\n",
" index = index + 1 # increment the position to search for the next character\n",
"\n",
"print(f\"The end index value is {index}\")\n",
"print(\"--------------------------------\")\n"
]
}
],
"metadata": {
"interpreter": {
"hash": "949777d72b0d2535278d3dc13498b2535136f6dfe0678499012e853ee9abcab1"
},
"kernelspec": {
"display_name": "Python 3.10.2 64-bit",
"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.10.2"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment