Dealing With Strings in Python
Dealing With Strings in Python
That said, let’s get to be more familiar with strings, functions and methods.
In Mathematics, from the set (domain), x={1,2,3}, we can have a new set (co-domain)
y=f(x)={2,4,6} if y=f(x)=2x.
In python,
x = "Hello World" # This is an argument.
y = len(x) # This takes x, the argument, finds its length, and returns 11.
print(x,"is", y, "characters long.") # This shows that x is not altered as the len() function
calculates the length of x, and assigns it to y.
Functions have their arguments in parentheses, while Methods begin with a period. Example:
x = "Hello World" # This is an argument.
print(x.replace("H","B")) # Prints "Bello World" .replace() is a method.
1 |B e y on d P a p e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)
You can extract the elements of a string by using indexes in square brackets. Indexing starts
with 0, meaning the first element (character) has an index of 0:
Text = "Beyond Papers"
print(Text[1]) # Prints "e"
print(Text[2:6]) # Prints "yond". This is called slicing, while the syntax [start:stop] is a slice
syntax. It will not include the character at the stop position.
print(Text[-5:-2]) # Prints "ape". Negative indexing counts, starting from the end of the string.
The lower() and casefold() methods return the string in lower case:
Text = "Beyond Papers"
print(Text.lower()) # Prints "beyond papers"
The upper() method returns the string in upper case, while the capitalize() method capitalizes
only the first character.
Text = "beyond papers"
print(Text.capitalize()) # Prints "Beyond papers"
To convert the all first characters of each word in a string to upper case, use the title() method:
print("1st beyondPapers workshop".title()) # Prints "1St Beyondpapers Workshop"
Notice that the character "s", since its coming after a non-alphabet character is also converted
to upper case.
The strip() method removes whitespaces from the beginning and end of a string:
Text = " 5 "
print(Text.strip()) # Prints "5"
Text = "Be*yond*Papers"
New = Text.split("*") # Returns a list, ['Be', 'yond', 'Papers']. It finds instances of the specified
character, and splits the string into substrings (or elements of a list).
print(New)
Strings are arrays (lists). We can check whether a specified string is in our string, using the in
and not in membership operators.
Text = "Today"
Available = "day" in Text
print(Available) # Prints True
The count() method returns the number of occurrences of a string (substring) in a string:
Text = "Ade is a boy. Ade is tall. Ade is Ade, and Ade is Ade’s name."
print(Text.count("Ade")) # Prints 6
print(Text.count("Ade", 14, 30)) # Prints 2. 14 and 30 are the start and stop indexes
respectively, within which the program searches. It starts counting from the substring found
on index 14, and ends on index 29 of the variable, Text.
print(Text.count("Ade", 14)) # Prints 5. Start and Stop indexes are optional. Here only the
Start index is used.
The find() and index() methods find the first occurrence of a string in a string, and returns its
position. If the value is not found, the find() method returns -1, while the index() method
raises an exception.
Text = "Beyond Papers"
print(Text.index("e")) # Prints 1
print(Text.find("E")) # Prints -1. "E" is not the same as "e". Python is ‘case-sensitive’.
They support the start and stop indexes too: string.find(value, start, stop).
The rfind() and rindex() methods search the string for the specified value, and return the
position of the last occurrence of the value in the string.
You can use the format() method to insert numbers into strings having placeholders {}.
Area = 15
print(Text.format(Area)) # Prints "The area of the rectangle is 15 centimeter-square."
Length = 5
Breadth = 3
Area = Length * Breadth
print(Text.format(Length, Breadth, Area)) # Prints "Length = 5\nBreadth = 3\nArea = 15".
You can index the placeholders when using unordered multiple arguments:
Text = """Length = {2}
Breadth = {0}
Area = {1}"""
Length = 5
Breadth = 3
Area = Length * Breadth
print(Text.format(Breadth, Area, Length))
4 |B e y on d P a p e r s