In any programming language, string manipulation is one of the most important aspect we can't live without. A string is something which holds any message or information. So, its important to know how to make some message or information from the available data. Python provides several ways of string manipulations which are highly optimized and concise.
String Operators
The + operator concatenates two strings.
a = "Hello "
b = "Alice! "
print(a + b)
# Output -> Hello Alice!
c = "Good morning!"
print(a + b + c)
# Output -> Hello Alice! Good morning!
The * operator repeats the string n number of times, where n is an integer mentioned as a right operand.
a = "echo"
print(a * 5)
# Output echoechoechoechoecho
The in operator takes two strings as operands and returns True if the string on the left side is contained in the string on the right side. It returns False otherwise.
a = "programming in python"
b = "python" in a
c = "code" in a
print(b) # Output True
print(c) # Output False
Indexing in strings
We can access a character or a part of string using [ ] index notation. Here are some examples.
Consider an example
s = "example.com"
You can access a particular character of a string by passing its index position in the index notation. The below statement will output e as the character e in example.com is at 0th position.
print(s[0])
Similarly, the character c in example.com is at 8th position, so you can access the character c like this.
print(s[8])
You can slice a portion of string with index notation. The representation is [<start-index>:<end-index>]. So the example below will select all characters starting from index 8 to index 11 from "example.com".
print(s[8:11])
This will print com.
Leaving start index blank will consider starting index as 0 by default. Leaving end index will consider the index number of the last character by default.
This will print "example".
print(s[:7])
This will print "com"
print(s[8:])
This will print "example.com"
print(s[:])
We can also jump forward by skipping some characters, this is where the third parameter comes in - the step-number. The representation is [<start-index>:<end-index>:<step-number>]
print(s[0:11:2]) # Output -> eapecm
print(s[::2] # Output -> eapecm
print(s[::3]) # Output -> emeo
String methods
Consider an example
s = "example.com"
Capitalize a string or make the first letter in capital
print(s.capitalize())
Counts the number of times a substring occurs in a string
print(s.count("e"))
Returns the index of the first substring that occurs in a string
print(s.index("m"))
Returns True if a string is a mix of alphabets and numbers
print("code001".isalnum())
Concatenates an array of string separated by the dilimeter by which the join method is called on.
print(", ".join(names))
Splits a string by dilimeter or substring and returns the splitted substrings in an array
print(s.split("."))
String with leading and trailing spaces
name = " Alice "
print("->|",name, "|<-")
print("->|",name.strip(), "|<-") # strip() remove leading and trailing spaces
Converts the string into upper case
print(s.upper())
zfill(num) is used to pad a numeric digit with 0s to the left.
print("1".zfill(4))
print("11".zfill(4))
print("111".zfill(4))
print("1111".zfill(4))
These are some frequently used string built-in functions
print(chr(115)) # Returns a character equivalent of a number
print(ord("s")) # Returns an integer equivalent of a character
print(len(s)) # Returns length of a string
names = ["Alice", "Bob"]
print(str(names)) # Returns string equivalent of an object
String formatting
You can do string formatting in various ways especially by using the above mentioned string function. However there is another way which allows us to do an inline string formatting in a clean and fancier way. This has been introduced in Python version 3.6 and above.
Such formatted strings are called Formatted string literals or f-string and the method is called String Interpolation
A simple example
name = "Alice"
welcomeText = f"Welcome {name}! Have a great day!"
print(welcomeText)
It supports number formatting as well
payeeName = "Bob"
billMonth = "September"
amount = 35.657448
text = f"Hello {payeeName}, your bill amount for the {billMonth} month is {amount:.2f} "
print(text)
In the above example we used : which is used to do any number formatting. So a number formatting mentioned on the right side of : will be applied to the left side string.
Any complex Python compatible expressions can be evaluated as well with interpolation. See an example below.
from Lib import datetime
currentHour = datetime.datetime.now().hour
greetText = f"Good {'Morning' if currentHour < 12 else 'Afternoon' if currentHour >= 12 and currentHour < 16 else 'Evening'}!"
text = f"Hello {payeeName}, \n{greetText} \nYour total bill for the {billMonth} month is {amount*1.05 :.2f} [Amount - {amount:.2f}, tax - {amount*0.05:.2f}]"
print(text)
Python jupyter notebook for code examples
Access Jupyter notebook for this chapter here:
Python Notebook - String Manipulation