Python: 18 String Programming questions and answers

In this post we will explored the most asked 18 python String Programming questions and answers

1. How to reverse a sentence in Python input by User

inputsentence = input("Please input  a sentence :")
print(" ".join(reversed(inputsentence.split())))

Output

Please input  a sentence :This is Python string example
example string Python is This

2. How to find the characters at an odd position in string input by User.

string = input("Enter the string : ")

outputString = ''

for i in range(len(string)):
    if(i % 2 == 0):
        outputString = outputString + string[i]
        
print("input string :  ", string)
print("String after odd charcater :", outputString)

Output

Enter the string : PythonString
input string :   PythonString
String after odd charcater : PtoSrn

3. How to check string start with specific character enter by the user.

we are using the startwith() method. It returns true if the string starts with a specified prefix or else returns false.

string = input("Enter the string : ")

result = string.startswith('Python')
print(result)

Output

Enter the string : Python program
True

4. How to remove all newline from the String.

inputString = '\nPython String\n with\n newline\n'
resultStr = inputString.replace("\n", "")

print(resultStr)

Output

Python String with newline

5.Different ways to get the filename without extension

import os
FilePath = os.path.basename('/document/imp/salary.txt')
#file name with extension
print(FilePath)
#get file name and extension
print(os.path.splitext(FilePath))
#file name without extension
print(os.path.splitext(FilePath)[0])

Output

salary.txt
('salary', '.txt')
salary

6. How to replace all occurrence of sub-string in string

inputStr = "is the is Python is Program is"
modifiedStr =  inputStr.replace('is', '')
print(modifiedStr)

Output

the  Python  Program

7. How to remove punctuation mark from list of string

listStr = ['', " 'Python'", " 'string'", " 'list of string'"]
modified_list = [item.replace("'", '') for item in listStr]
print(modified_list)

Output

['', ' Python', ' string', ' list of string']

8. How to find the number of matching characters in two string

import re 
string1 = "Python"
string2 = "PythonProgram"
  
match_char_count = 0
for char in string1: 
    if re.search(char,string2): 
        match_char_count = match_char_count+1
print("matching charcter counts = ", match_char_count) 

Output

matching charcter counts =  6

9. How to convert a string in list.

Countries = 'India, USA, Japan, Russia, UK'
print(list(Countries.split(', ')))

Output

['India', 'USA', 'Japan', 'Russia', 'UK']

10.How to find the Domain name from a string

import tldextract
Fullurl = 'https://www.devenum.com/cyber-security-tutorial/'

Domain_Information = tldextract.extract(Fullurl)

print("Domain Name: ", Domain_Information.domain)

print("Full Domain name: ", '.'.join(Domain_Information))

Output

Domain Name:  devenum
Full Domain  name:  www.devenum.com

11. How to convert all string elements of list to int.

  
numlst = ['20', '50', '100', '345', '609'] 

numlst = [int(num) for num in numlst ] 
  
print ("all string elements to int in list  : " ,numlst) 

Output

all string elements to int in list  :  [20, 50, 100, 345, 609]

12.Count Total numbers of upper case and lower case characters in input string

here we are using isupper() to find upper case characters and islower() to find the lower case characters

string = input('Please enter the string: ')
upper_case= 0
lower_case = 0
    
for char in string:
 if char.isupper():
    upper_case+=1
 elif char.islower():
    lower_case+=1
       
print ("string entered by user : ", string)
print (" Total Upper case characters  : ", upper_case)
print ("Total Lower case Characters : ", lower_case)
   

Output

Please enter the string: Let us Learn Python

string entered by user :  Let us Learn Python

 Total Upper case characters  :  3

Total Lower case Characters :  13

13.Program to find vowels in a string

Here we are checking upper case and lower case vowels characters.

input_string =input('Enter the string :')
vowels = "AaEeIiOoUu"

Vowel_found = [char for char in input_string if char in vowels] 
print('no of vowels found =',len(Vowel_found)) 
print('Vowels found = ',Vowel_found) 
      

Output

Enter the string :DataScience
no of vowels found = 5
Vowels found =  ['a', 'a', 'i', 'e', 'e']

14. How to reverse a user input string

input_string = input('Please Enter the string:')

reversed_str =''.join(reversed(input_string))

print('reversed string =',reversed_str)
    

Output

Please Enter the string:Manual
reversed string = launaM    

15. Program to sort a string in Python

input_string = input('Please Enter the string:')

sortedStr = sorted(sorted(input_string), key= str.upper)

print('sorted String =',sortedStr)

Output

Please Enter the string:Manual
sorted String= ['a', 'a', 'l', 'M', 'n', 'u']

16. How to print input string in upper case and lower case

input_string = input('Please Enter the string:')


print('input string lower case   =',input_string.lower())

print('input string to upper case   =',input_string.upper())

Output

Please Enter the string:Python Language
input string lower case   = python language
input string to upper case   = PYTHON LANGUAGE

17. How To Extract URL From A String In Python?

#How to Extract URL from a string in Python?
 
import re
 
def URLsearch(stringinput):
 
  #regular expression
 
 regularex = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))))+(?:(([^\s()<>]+|(([^\s()<>]+))))|[^\s`!()[]{};:'\".,<>?«»“”‘’]))"
 
 #finding the url in passed string
 
 urlsrc = re.findall(regularex,stringinput)
 
 #return the found website url
 
 return [url[0] for url in urlsrc]
 
textcontent = 'text :a software website find contents related to technology https://devenum.com https://google.com,http://devenum.com'
 
#using the above define function
 
print("Urls found: ", URLsearch(textcontent))

Output

Urls found:  ['https://devenum.com', 'https://google.com,http://devenum.com']

18. Convert Int To String In Python

str() function is in built function in python that you can use to convert a number to string using these below steps.

variable = 55
print(type(variable))
string_num = str(variable)
print(type(string_num))

Output

<class 'int'>
<class 'str'>