Python Practice Strings

In this class, We do Python Practice Strings.

For Complete YouTube Video: Click Here

These examples will help the reader to improve his coding skill.

These examples will improve the reader understanding. They can crack campus placement exams easily.

For better practice, try to solve on your own, then check for a solution.

Take complete placement training course and practise tests.

Q1)
What is the output displayed by the below code?
string="hello######hi### ###how#are#you"
output = [s for s in string.split('#') if s]
print(output)

In the above program, We used the list comprehensions.

To know list comprehension. Click here.

The given string split using #. and there is an if condition.

They used the if condition to eliminate the empty strings.

Given below is the output displayed by the program.

['hello', 'hi', ' ', 'how', 'are', 'you']
Q2)
What is the output displayed by the below code?

import re
string="""hello how are you
he is working in placement program"""
for i in string.split():
    if re.search('...(.)*',i):
        print(i)

In the above program, we have a multi-line string.

When using the split method on strings, the split happens in space and a new line.

The words are taken after the split and used regular expressions to select the words with a minimum of three characters.

Dot in regular expressions is used to represent a character.

Given below is the output displayed by the program.

hello
how
are
you
working
placement
program
Q3)
What is the output displayed by the below code?

def isPalindrome(n):
    return str(n)[::-1]==str(n)
def rev(n):
    return int(str(n)[::-1]) 
n=int(input())
n=n+rev(n)
if(isPalindrome(n)):
    print(n,"is palindrome")
else:
    print(n,"is not palindrome")

In the above program, the function rev is used to reverse the string.

To reverse the string, we use the concept of slicing.

[::-1] slicing is used to reverse the given string. After reversing, we convert the string to an integer.

The input is added with the reverse of the input value and sent to check palindrome or not.

The palindrome function will check palindrome or not using the concept of string reverse.

Output:
124
545 is palindrome