Most Useful String Functions in Python
Most Useful String Functions in Python
1. len(str) : Returns Length of String
str=input("Enter String : ")
print("LENGTH OF ",str," : ",len(str))
--------------------------------------------
2. str.upper() : Converts all characters in the string to uppercase.
str=input("Enter String in Lower Case Letter : ")
print(str.upper())
--------------------------------------------
3. str.lower() : Converts all characters in the string to lowercase.
str=input("Enter String in UPPER Case Letter : ")
print(str.lower())
4. str.capitalize() : Capitalizes the first letter of the string and converts all
other characters to lowercase.
str=input("Enter String in lower Case Letter : ")
print(str.capitalize())
5. str.title() : Capitalizes the first letter of each word in the string.
str=input("Enter String in lower Case Letter : ")
print(str.title())
--------------------------------------------
6. str.strip() : Removes any leading and trailing whitespaces.
str=input("Enter String with some whitw spaces before and after string :
")
print(str.strip())
--------------------------------------------
7. str.split(separator) : Splits the string into a list of substrings based on the specified separator.
str=input("Enter String with separator : ")
print(str.split(","))
--------------------------------------------
8. str.join(iterable) : Joins the elements of an iterable (e.g., list) into a
single string, with the specified separator
",".join(["hello", "world"]) # Output:
"hello,world" - Can Execute on REPL Directly
str=input("Enter String with separator : ")
print(str.split(","))
---------------------------------------------
9. str.replace(old, new): Replaces all occurrences of a substring with another substring.
str="Hello World"
print(str.replace('World','Python'))
---------------------------------------------
10. str.find(substring) : Returns the index of the first occurrence of the substring, or -1 if not found.
indexString=input("ENTER SUBSTRING YOU WANT TO SEARCH : ")
index=str.find(indexString)
print(index)
---------------------------------------------
11. str.startswith(prefix) : Checks if the string starts with the specified prefix.
str="Hello World"
print(str.startswith('Hell')) # Returns True
---------------------------------------------
12. str.endswith(suffix) : Checks if the string ends with the specified suffix.
str="Hello World"
print(str.endswith('ld'))
---------------------------------------------
13. str.isdigit() : Checks if all characters in the string are digits.
print(str.isdigit())
print(str.isalpha())
15. str.isalnum() : Checks if all characters in the string are alphanumeric (letters and numbers).
str="emp001cse"
print(str.isalnum())
16. Reversing a String : You can reverse a string using slicing with a negative step.
The slice
[::-1] starts from the end of the string and steps backwards.
print(str[::-1])
Comments
Post a Comment