Python String Functions
String functions
String data type in Python has many inbuilt functions which makes it easier to work with strings.
Consider the string, name=“Raghav”.
Function |
Output |
Explanation |
name.count("a") |
2 |
Returns the count of a given set of characters. Returns 0 if not found |
name.replace("a","A") |
RAghAv |
Returns a new string by replacing a set of characters with another set of characters. It does not modify the original string |
name.find("a") |
1 |
Returns the first index position of a given set of characters |
name.startswith("Ra") |
True |
Checks if a string starts with a specific set of characters, returns true or false accordingly. |
name.endswith("ha") |
False |
Checks if a string ends with a specific set of characters, returns true or false accordingly. |
name.isdigit() |
False |
Checks if all the characters in the string are numbers, returns true or false accordingly. |
name.upper() |
RAGHAV |
Converts the lowercase letters in string to uppercase |
name.lower() |
raghav |
Converts the uppercase letters in string to lowercase |
name.split("a") |
[‘R’, ‘gh’, ‘v’] |
Splits string according to delimiter and returns the list of substring. Space is considered as the default delimiter. |
Tryout
Tryout the below code in python playground and observe the output.
CODE/PROGRAM/EXAMPLE
boarding_call="Good Evening, this is the final call to AL passengers for the flight AL 466 which is planned to take off at 8.40A.M."
if(boarding_call.startswith("Good Evening")):
print(boarding_call.replace("Good Evening","Good Morning"))
if(boarding_call.find("AL"))>=0:
print("Welcome to Air Lines.")
if(boarding_call.endswith("A.M.")):
print("Passengers are requested to have their breakfast.")
a=boarding_call.split(" ")
for i in a:
if(i.isdigit()):
print("Flight Number is specified to the passengers.")
print("Total number of times flight service name is specified in the boarding call:",boarding_call.count("AL"))
message="Thank you all..Have a nice journey!"
print(message.upper())
print(message.lower())