Some Basic Python String Programs-2


Python Program to split a string into groups of n consecutive characters

string = "Beta Python: Python for U"
n = 5
split_string = [(string[ch:ch+n]) for ch in range(0, len(string), n)] #list comprehension 
print(split_string)
#Output: ['Beta ', 'Pytho', 'n: Py', 'thon ', 'for U']
  • List comprehension is a compact method that defines a list and its contents at the same time. Its basic syntax consists of a square bracket with an expression that is executed for each element along with for loop to iterate over each element. Read more: List Comprehension in Python – Explained with Examples

Python Program to check if a string is a subset of another string

str1 = "Beta Python: Python for U"
str2 = "tPoU"

#using all() 
subset1 = all(ele in str1 for ele in str2)
if subset1: 
    print(f"\'{str2}\' is a subset of \'{str1}\'")
else:
    print(f"\'{str2}\' is not a subset of \'{str1}\'")
#Output: 'tPoU' is a subset of 'Beta Python: Python for U'

#using issubset()
subset2 = set(str2).issubset(str1)
if subset2: 
    print(f"\'{str2}\' is a subset of \'{str1}\'")
else:
    print(f"\'{str2}\' is not a subset of \'{str1}\'")
#Output: 'tPoU' is a subset of 'Beta Python: Python for U'
  • The all() built-in method returns True If all the elements in the iterable passed are true else it returns False.
  • 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.
  • The format() built-in string method returns a formatted representation of the string controlled by the format specifier. The prefix f before a string tells Python that the string is a format string. The replacement fields are expressions enclosed in curly brackets in a format string. They are evaluated at run time and then formatted.
  • The backslash (“\”) character used as escape characters, directs the compiler to take a suitable action mapped to character prefixed with it.
  • The issubset() built-in method returns True if all the elements of a set are present in the iterable passed else it returns False.

Python Program to remove multiple empty spaces from a string List

str_list1 = ['Beta ', " " ,'Python', "", ":", 'Python ', " ", 'for', " ", " ", " U"] 
str_list2 = [ele for ele in str_list1 if ele.strip()]
print(str_list2)
#Output: ['Beta ', 'Python', ':', 'Python ', 'for', ' U']
  • The strip() built-in string method removes any spaces present at the beginning and the end of the string.

Python program to count words in a sentence

string = "Beta Python: Python for U"
words_count = len(string.split())
print(words_count)
#Output: 5
  • The split() built-in method breaks up a string by the specified separator and returns a list of strings. If a separator is not specified then white space is considered as a separator.
  • The len() built-in function returns the number of elements present in a container.

Python program to add leading Zeros to a string

str1 = "BetaPython"

#using rjust()
str2 = str1.rjust(5 + len(str1), '0')
print(str2)
#Output: 00000BetaPython

#using zfill()
str3 = str1.zfill(5 + len(str1))
print(str3) 
#Output: 00000BetaPython
  • The rjust() built-in string method returns a new string of given length after filling the remaining space on the left side of the original string with the character specified.
  • The zfill() built-in string method returns a copy of the string with ‘0’ characters padded to the left side of the original string.

Python program to add trailing Zeros to a string

str1 = "BetaPython"
 
#using ljust() 
str2 = str1.ljust(5 + len(str1), '0') 
print(str2) 
#Output: BetaPython00000

#using format()
str3 = '{:<015}'.format(str1)
print(str3) 
#Output: BetaPython00000
  • The ljust() built-in string method returns a new string of given length after filling the remaining space on the right side of the original string with the character specified.
  • The operator ‘<‘  is used to left-align the string and fill the remaining space of the length given with the character specified.

Python program to Right and Left Shift characters in a String

str1 = "Beta Python: Python for U"
r_swift = 4
l_swift = 3

#using * operator
str2 = (str1 *3)[len(str1) + r_swift - l_swift: 2 * len(str1) + r_swift - l_swift] #selectively slicing the string to get required string
print(str2) 
#Output: eta Python: Python for UB

#using % operator
pos = (r_swift - l_swift) % len(str1) #the mod of the right swift and the left swift difference with length computes the string positions
str3 = str1[pos:] + str1[: pos]
print(str3) 
#Output: eta Python: Python for UB
  • The ‘*’ is used to repeat the string for a given number of times when used with a string type.
  • 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(modulus operator) returns the remainder of the left operand by the right.
  • The ‘+’ operator concatenates multiple strings to a single string.

Related Posts-

Leave a Comment

%d bloggers like this: