#!/usr/bin/env python # coding: utf-8 # # String Operators # ## + operator # In[1]: a = "Hello " b = "Alice! " print(a + b) c = "Good morning!" print(a+b+c) # # * operator # In[2]: a = "echo" print(a * 5) # ## in operator # In[3]: a = "programming in python" b = "python" c = "code" print(b in a) print(c in a) # # Indexing in strings # In[4]: s = "example.com" print(s[0]) print(s[8]) print(s[8:11]) print(s[:7]) print(s[8:]) print(s[:]) print(s[0:11:2]) print(s[0:11:3]) # # String functions # **Capitalize a string or make the first letter in capital** # In[5]: print(s.capitalize()) # **Returns the total number of characters in a string** # In[6]: print(len(s)) # **Counts the number of times a substring occurs in a string** # In[7]: print(s.count("e")) # **Returns the index of the first substring that occurs in a string** # In[8]: print(s.index("m")) # **Returns True if a string is a mix of alphabets and numbers** # In[9]: print("code001".isalnum()) # **Concatenates an array of string separated by the dilimeter by which the join method is called on.** # In[10]: names = ["Alice", "Bob"] print(", ".join(names)) # **Splits a string by dilimeter or substring and returns the splitted substrings in an array** # In[11]: print(s.split(".")) # **Remove leading and trailing spaces** # In[12]: name = " Alice " # <- String with leading and trailing spaces print("->|",name, "|<-") print("->|",name.strip(), "|<-") # Removed leading and trailing spaces # **Coverts the string into uppercase** # In[13]: print(s.upper()) # **zfill is used to pad a numeric digit with 0s to the left.** # In[14]: print("1".zfill(4)) print("11".zfill(4)) print("111".zfill(4)) print("1111".zfill(4)) # **Some frequently used string built-in functions** # In[15]: 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 print(str(names)) # Returns string equivalent of an object # # String formatting # Example 1: # In[16]: name = "Alice" welcomeText = f"Welcome {name}! Have a great day!" print(welcomeText) # Example 2: # In[17]: payeeName = "Bob" billMonth = "September" amount = 35.657448 text = f"Hello {payeeName}, your bill amount for the {billMonth} month is {amount:.2f} " print(text) # Example 3 : Any complicated Python compatible expressions can be evaluated as well with interpolation. # In[18]: currentHour = 10 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)