Introduction to Strings
Strings in Python & in programming languages in general are a way of storing data that is text.
Examples include:
Hello World
My name is Xavier
Javascript > Python
Strings are always surrounded with single or double quotes. Both have the same effect, but stick with the one you choose to use.
print("Welcome")
print("Hello!")
print("123")
Did you see that? We can have numbers as strings too! So long as a number is encapsulated in quotations, then it’s considered to be a str and not a int or a float, which are the data types usually associated to numbers.
Basic String Operations
Strings in Python are very flexible and can be manipulated in a mulititude of ways. In this section, we’ll being over what these “ways” are.
Concatenation
One of the main things that can be done with strings is connecting them together, formally known as concatenation.
print("Hello, " + "World!")
print("1" + "2" + "3")
Hello, World!
123
While in the examples above, the reason why we would concatenate isn’t made clear, the reason concatenation is so useful is when we have two or more variables that may not be statically defined, we can combine them together to form a cohesive string.
x = input("What's your first name?")
y = input("what's your last name?")
print("Your name is: " + x + " " + y)
Your name is: Xavier Thompson
Repetition / Multiplication
A really cool feature of python that isn’t avaliable in other languages is it’s ability to multiply strings like you would with an integer.
#Repetition
color = "Green"
repeat_color = color * 3
print(repeat_color)
GreenGreenGreen
The usage of multiplying text in Python isn’t used in most circumstances, but when it comes to making something artistic of out text (ASCII Art), then this feature of python may come in handy later on.
Indexing
Indexing is the process of accessing a specific char (or sequence of chars) in a string. Each character in a string is assigned two numbers that is used to identify its position in a string. Take the following string:
“HELLO”
When indexing, it’s best to look at HELLO from its constituent parts.
['H'] ['E'] ['L'] ['L'] ['O']
Intutively, we would imagine that H would be assigned 1 as its the first character, however an important fact to note is in programming, we start counting at 0. So H would be assigned 0, E would be assigned 1, and so on.
# Stored String
greeting = "HELLO"
#Indexes
print(greeting[0])
print(greeting[4])
print(greeting[3])
print(greeting[1])
H
O
L
E
However, as mentioned before, characters in a string are assigned two numbers which can be used to index them from the string. Positive numbers & negative ones. The negative ones allow you to start at the end of the string instead.
# Stored String
greeting = "HELLO"
print(greeting[-1])
print(greeting[-5])
O
H
String Slicing
String slicing is a expanded version of indexing, which instead of taking only one character, we can take multiple characters in a string.
Bellow illustrates how this can be done:
element = "Hydrogen"
print(element[0:5])
Hydro
To index a section you begin with the starting character (0) and end with the index of the last character + 1.
In this case of 0:5, 0 is inclusive (the character with index 0 is included), while 5 is exclusive (the character with index 5 is excluded). So that’s why the character , “g” which has an index of 5 isn’t included despite being a part of the slice 0:5
This is essentially the basics in which you can do to index anything but there are some important concepts to note:
element = "Lithium"
# Specify an entire String
print(element[:])
# Reverse a String
print(element[::-1])
# Indexing a character after every x number of characters
print(element[1::2])
Lithium
muihtiL
ihu
String Methods
The most powerful thing about strings is its ability to be manipulated via methods which are functions that change the string in a unique way.
We’ll list some of the most commonly used functions & how to implement them.
# Implementing a basic method
name = "vasanth"
capitalized_name = name.capitalize()
print(capitalized_name)
Vasanth
In the example above you see in order to implement a method you take the variable then add .function-name() to the end of it. However as mentioned before, there are countless methods that can be used, some which are shown below:
name = "vasanth rajasekaran"
language = "English"
# To capitalize multiple words, use title method
capitalize_full_name = name.title()
print(capitalize_full_name)
# UPPERCASE a string
uppercase_string = name.upper()
print(uppercase_string)
# Count characters in string
print(len(language))
Vasanth Rajasekaran
VASANTH RAJASEKARAN
7
The power of string methods can’t be stressed enough, so be sure to take a look at the many avaliable methods offered in Python
Here’s a website you can look into to: Python Methods List
Hacks / Homework
- Hack 1: Write a Python function that takes a string as input and returns the string reversed.
- Hack 2: Create a Python program that counts the number of vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) in a given string.
- Hack 3: Given a string, write a function to replace all occurrences of the substring ‘abc’ with ‘xyz’.
- Hack 4: Write a function that checks if a given string is a palindrome (reads the same forward and backward), ignoring spaces, punctuation, and case.
- Hack 5: Write a program that finds and returns the longest word in a given sentence.
CHALLENGING QUESTION:
- Hack 6: Given a string containing both letters and digits, write a function that extracts all the numbers, sums them up, and returns the total.