Guide to Python (University at Buffalo Version)
Chapter 8: Working With Strings
Python Strings
Python provides many methods to maniplulate strings. Strings are not mutable. Below are a few examples.
# string_for.py myString = "Welcome to Python!" for c in myString: print(c)
W e l c o m e t o P y t h o n !
# string_count.py myString = "Welcome to Python!" print(f"The Letter o appears {myString.count('o')} times.")Figure 8-3: String count()
Method Code
The Letter o appears 3 times.
count()
Method Output# string_methods.py myString = "Welcome to Python!" print(f"myString = {myString}") lower = myString.lower(); print(f"using lower = {lower}") upper = myString.upper(); print(f"using upper = {upper}") cap = myString.capitalize(); print(f"using capitalize = {cap}")
capitalize()
upper(), and upper()
Methods CodeMyString = Welcome to Python! using lower = welcome to python! using upper = WELCOME TO PYTHON! using capitalize = Welcome to python!
capitalize()
, upper()
, and upper()
Methods CodeFormatting Python Strings Using the format()
Method
Python provides many Formatting types for usng the format()
method to format strings. Below are a few examples.
print("Using placeholders") str1 = "My name is {firstName}, I teach in the {dept}" str1 += " Department.".format(firstName = "Jim", dept = "CIS") str2 = "My name is {0}, I teach in the {1}" str2 += " Department.".format("Jim", "CIS") flowersArray = ["Rose", "Red", 19.95] largeNumber = 123456789.12 print("str1 =", str1) print("str2 =", str2) print("largeNumber =", largeNumber) print("-----") print("Left Aligning data using the :> characters") print("-----") print(f"| {flowersArray[0]:>10} | {flowersArray[1]:>10} | {flowersArray[2]:>5} |") print("-----") print("Right Aligning data using the :< characters") print(f"| {flowersArray[0]:<10} | {flowersArray[1]:<10} | {flowersArray[2]:<5} |") print("-----") print("Center Aligning data using the :^ characters") print(f"| {flowersArray[0]:^10} | {flowersArray[1]:^10} | {flowersArray[2]:^5} |") print("-----") print("Formatting the currency") print(f"| {flowersArray[0]:^10} | {flowersArray[1]:^10} | ${flowersArray[2]:>5.2f} |") print("-----") print("Formatting a number")|") print(f"{largeNumber:,.2f}")
format()
Method CodeUsing placeholders str1 = My name is Jim, I teach in the CIS Department. str2 = My name is Jim, I teach in the CIS Department. largeNumber = 123456789.12 ----- Left Aligning data using the :> characters | Rose | Red | 19.95 | ----- Right Aligning data using the :< characters | Rose | Red | 19.95 | ----- Center Aligning data using the :^ characters | Rose | Red | 19.95 | ----- Formatting the currency | Rose | Red | $19.95 | ----- Formatting a number 123,456,789.12
format()
Method Output