a = "Hello "
b = "Alice! "
print(a + b)
c = "Good morning!"
print(a+b+c)
Hello Alice! Hello Alice! Good morning!
a = "echo"
print(a * 5)
echoechoechoechoecho
a = "programming in python"
b = "python"
c = "code"
print(b in a)
print(c in a)
True False
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])
e c com example com example.com eapecm emeo
Capitalize a string or make the first letter in capital
print(s.capitalize())
Example.com
Returns the total number of characters in a string
print(len(s))
11
Counts the number of times a substring occurs in a string
print(s.count("e"))
2
Returns the index of the first substring that occurs in a string
print(s.index("m"))
3
Returns True if a string is a mix of alphabets and numbers
print("code001".isalnum())
True
Concatenates an array of string separated by the dilimeter by which the join method is called on.
names = ["Alice", "Bob"]
print(", ".join(names))
Alice, Bob
Splits a string by dilimeter or substring and returns the splitted substrings in an array
print(s.split("."))
['example', 'com']
Remove leading and trailing spaces
name = " Alice " # <- String with leading and trailing spaces
print("->|",name, "|<-")
print("->|",name.strip(), "|<-") # Removed leading and trailing spaces
->| Alice |<- ->| Alice |<-
Coverts the string into uppercase
print(s.upper())
EXAMPLE.COM
zfill 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))
0001 0011 0111 1111
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
print(str(names)) # Returns string equivalent of an object
s 115 11 ['Alice', 'Bob']
Example 1:
name = "Alice"
welcomeText = f"Welcome {name}! Have a great day!"
print(welcomeText)
Welcome Alice! Have a great day!
Example 2:
payeeName = "Bob"
billMonth = "September"
amount = 35.657448
text = f"Hello {payeeName}, your bill amount for the {billMonth} month is {amount:.2f} "
print(text)
Hello Bob, your bill amount for the September month is 35.66
Example 3 : Any complicated Python compatible expressions can be evaluated as well with interpolation.
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)
Hello Bob, Good Morning! Your total bill for the September month is 37.44 [Amount - 35.66, tax - 1.78]