Some Basic Python String Programs-3

Python program to move Word to Rear-end

str1 = "Beta Python: Python for U "
word = "Python"

#using slicing and find() 
str2 = str1[:str1.find(word)] + str1[str1.find(word) + len(word):] + word
print(str2)
#Output: Beta : Python for U Python

#using replace()
str3 = str1.replace(word,"") + word
print(str3)
#Output: Beta :  for U Python
  • Slicing extracts a subset of elements from a sequence. It mainly uses three parameters strat, stop, and step enclosed in square brackets []. Read more: Slicing in python
  • The ‘+’ operator concatenates multiple strings to a single string.
  • The find() built-in string method returns the lowest index of the substring where it is found in the given string. If it is not found then it returns -1.
  • The replace() built-in string method returns a copy of the string where all occurrences of a substring are replaced with another substring in the string.

Python program to print the floating number up to 2 decimal places

num = 3.141526
print("{:.2f}".format(num))
#Output: 3.14
  • The format() built-in string method returns a formatted representation of the string controlled by the format specifier. The replacement fields are expressions enclosed in curly brackets in a format string. They are evaluated at run time and then formatted. The ‘f’ is a type option that specifies the number is of float type. The ‘.’ is a precision operator that sets the precision of the given floating number.

Python program to find the distance between occurrences

string = "Beta Python: Python for U "
sub = "Python"

#using index()
dist1 = string.index(sub, string.index(sub) + 1) - string.index(sub)
print(dist1)
#Output: 8

#using find() and rfind()
dist2 = string.rfind(sub) - string.find(sub)
print(dist2) 
#Output: 8
  • The index() built-in string method returns the lowest index of the substring where it is found in the given string. If it is not found then it throws an exception.
  • The rfind() built-in string method returns the highest index of the substring where it is found in the given string. If it is not found then it returns -1.

Python program to print iterative Pair Pattern

ele1 = "BetaPython"
ele2 = "*"
repeat = 5
pattern = ele1.join(ele2 * i for i in range(repeat + 1))
print(pattern)
#Output: BetaPython*BetaPython**BetaPython***BetaPython****BetaPython*****
  • The join() built-in string method combines the parameters passed with the string and returns a concatenated string.

Python program to check if a string is palindrome or not

string = "abbbabbba"
if string == string[::-1]:
    print("String is palindrome")
else:
    print("String is not palindrome")
  • A palindrome sequence reads the same from the beginning as well as from the end.
  • Python allows negative indexing i.e. indexing from the end of the list using a negative number. Read more: What is indexing, iterating and enumerating in python?
  • Python treats everything as an object and objects are always true in python. However, null values, None, 0, empty data types are observed as false in python.

Python program to check if a string contains only numbers

string = "0123456789"

#using try and except
try:
    num = int(string)
    print(f"All the elements in the {string} are numbers")
except:
    print(f"All the elements in the {string} are not numbers")
#Output: All the elements in the 0123456789 are numbers

#using isdigit()
if string.isdigit():
    print(f"All the elements in the {string} are numbers")
else: 
    print(f"All the elements in the {string} are not numbers")
#Output: All the elements in the 0123456789 are numbers
  • The try and catch statements are used to handle exceptions in python. Exceptions are raised when the program encounters an error. The critical code which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. If any exception occurs, the try clause gets skipped and except clause starts running else the try clause gets executed and the except clause gets skipped.
  • The int() built-in method returns an integer object from any number or string passed.
  • The isdigit() built-in string method returns True if all characters in the string are digits, else, it returns False.

Python program to check if a string contains only letters

string = "BetaPython"
if string.isalpha():
    print(f"All the elements in the {string} are letters") 
else: 
    print(f"All the elements in the {string} are not letters") 
#Output: All the elements in the BetaPython are letters
  • The isalpha() built-in string method returns True if all characters in the string are alphabets, else, it returns False.

Python program to check if a variable is a string

string = "Beta Python: Python for U"

#using isinstance()
if isinstance(string, str):
    print(f"{string} is a string")
else:
    print(f"{string} is not a string")
#Output: Beta Python: Python for U is a string

#using type()
if type(string) == str:
    print(f"{string} is a string") 
else:
    print(f"{string} is not a string")
#Output: Beta Python: Python for U is a string
  • The built-in instance() function returns True if the object is an instance or subclass of a class, else, it returns False.
  • The built-in type() function returns the type of the object passed.

Related Posts-

Leave a Comment

%d bloggers like this: