Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

Advance String tutorials in Python , Advance String-based python interview questions

String Programming in Python

String in Python

A string is a collection of characters. Index starts from 0 to size-1.

Strings can be written in:

a = 'hello'      # single quote
a = "hello"      # double quote
a = """hello"""  # triple quote

Index positions for string s = "hello":

s[0] = h
s[1] = e
s[2] = l
s[3] = l
s[4] = o

Q1) WAP to count vowels and consonants

s = "hello"
c1 = 0
c2 = 0

for i in range(len(s)):
    if s[i] in ('a','e','i','o','u'):
        c1 += 1
    else:
        c2 += 1

print("total vowel =", c1, " total consonant =", c2)

Q2) Check whether a string is palindrome

s = input("enter string")
size = len(s) - 1
c = 1

for i in range(0, len(s)//2):
    if s[i] != s[size - i]:
        c = 0
        print("not palindrome")
        break

if c == 1:
    print("palindrome")

Q3) WAP to find max character in string

s = "hellop"
max = s[0]

for i in range(1, len(s)):
    if max < s[i]:
        max = s[i]

print(max)

Q4) Validate Email

s = "@abcg.mailcom"
atpos = 0
dotpos = 0

for i in range(len(s)):
    if s[i] == "@":
        atpos = i
    if s[i] == ".":
        dotpos = i

if atpos > 0 and (dotpos - atpos) >= 2:
    print("valid email id")
else:
    print("invalid email id")

Other String Validation Questions

  • Validate mobile number
  • Validate first name and last name
  • Check strong/weak password
  • Find largest palindrome substring
  • Find max char in each word
  • Replace white space with underscore
  • Count uppercase, lowercase, digits, special characters

Example: Check Strong or Weak Password

s = "abCA@$_123"
sc = 0
chkcase = 0

for data in s:
    if data in ('@', '$', '_', '#', '!'):
        sc += 1
    if ord(data) >= 65 and ord(data) <= 91:
        chkcase += 1

if len(s) > 5 and sc > 2 and chkcase > 1:
    print("strong password")
else:
    print("weak password")

Reverse Each Word in String

s = "C CPP DS Java PHP"
s = s + " "
x = []
data = ""

for i in range(len(s)):
    if s[i] != " ":
        data += s[i]
    else:
        x.append(data)
        data = ""

for i in range(len(x)):
    d = x[i]
    for j in range(len(d)-1, -1, -1):
        print(d[j], end="")
    print()

More String Programming Questions

  • Remove all duplicates from a string
  • Remove characters from string1 which exist in string2
  • Check if two strings are rotations of each other
  • Reverse string recursively and iteratively
  • Print all permutations of a string
  • Find first non-repeating character
  • Reverse words in a sentence
  • Find smallest substring containing all chars of another string
  • Check if two strings are anagrams
  • Convert string to integer (implement atoi)

Predefined String Methods in Python

Method Description
capitalize()Converts first character to uppercase
center()Pads the string with characters
casefold()Converts to case-folded string
count()Counts substring occurrence
endswith()Checks suffix
expandtabs()Replaces tabs with spaces
encode()Encodes string
find()Returns first index of substring
format()Formats string
index()Returns index of substring
isalnum()Checks alphanumeric
isalpha()Checks alphabets only
isdecimal()Checks decimal chars
isdigit()Checks digits only
isidentifier()Checks valid identifier
islower()Checks lowercase
isnumeric()Checks numeric
isprintable()Checks printable chars
isspace()Checks whitespace
istitle()Checks title case
isupper()Checks uppercase
join()Concatenates iterable items
ljust()Left-justifies string
rjust()Right-justifies string
lower()Converts to lowercase
upper()Converts to uppercase
swapcase()Swaps case
lstrip()Removes leading characters
rstrip()Removes trailing characters
strip()Removes leading/trailing characters
partition()Splits into 3 parts
maketrans()Creates translation table
translate()Maps characters
replace()Replaces substring
rfind()Finds substring from right
rindex()Rightmost index
split()Splits string
rsplit()Splits from right
splitlines()Splits by line breaks
startswith()Checks prefix
title()Title-case string
zfill()Pads with zeros
format_map()Formats using dictionary

Built-in Functions Used with String

  • any() – True if any element is true
  • all() – True if all elements are true
  • ascii()
  • bool()
  • bytearray()
  • bytes()
  • compile()
  • complex()
  • enumerate()
  • filter()
  • float()
  • input()
  • int()
  • iter()
  • len()
  • max()
  • min()
  • map()
  • ord()
  • reversed()
  • slice()
  • sorted()
  • sum()
  • zip()

Post a Comment

16 Comments

  1. s = "ssssss ram madam jjjjjjjjjj kkk ppp ram hari sdafdfsafds dzfv"
    s1= s+ " ";
    lst=[]
    data=''
    for i in range(0,len(s1)):

    if s1[i]!= " ":
    data=data+s1[i]
    else:
    lst.append(data)
    data=''


    #print(lst)
    m=0
    for i in range(0,len(lst)):
    s2=lst[i]
    for j in range (0 ,len(s2)//2):
    if s2[j]!=s2[(len(s2)-1)-j]:
    break
    else:
    if m<len(s2):
    m=len(s2)
    index=i



    print(lst[index])



    ReplyDelete
  2. WAP to validate the mobile number

    s=input("mobile number")
    if len(s)==10 and s[0]!="0":
    print("valid")
    else:
    print("inavlid")

    ReplyDelete
  3. WAP to validate first name and last name

    a=input("enter full name")
    c=0
    for i in range(0,len(a)):
    if a[i].isspace():
    c=c+1
    if c==1 and a[0].isspace()==False:

    print("valid name")
    else:
    print("invalid name")

    ReplyDelete
  4. WAP to provide a weak password and Strong password

    p=input("enter password")
    d=0
    u=0
    l=0
    s=["@","#","*","&","^","$","!"]
    sc=0
    for i in p:
    if i in s:
    sc=sc+1
    if i.isdigit():
    d=d+1
    if i.isupper():
    u=u+1
    if i.islower():
    l=l+1
    if len(p)>7 and sc>0 and d>0 and u>0 and l>0:
    print("strong password")
    else:
    print("weak password")

    ReplyDelete
  5. WAP to find the largest palindrome in String

    a=input("enter palindrome")
    s=a.split(" ")
    max1=""
    for i in s:
    if len(i)>len(max1):
    max1=i
    else:
    continue
    if max1[::-1]==max1:
    print("longest palindrome is",max1)
    else:
    print("no")

    ReplyDelete
  6. WAP to find max char in each string in a word

    a=input("enter word")
    m=65
    for i in a:
    if ord(i)>m:
    m=ord(i)
    print(chr(m))

    ReplyDelete
  7. WAP to replace white space with an underscore

    a=input("enter name")
    s=""
    for i in range(0,len(a)):
    if a[i].isspace():
    s=s+"_"
    else:
    s=s+a[i]

    print(s)

    ReplyDelete
  8. WAP to count total upper case, lower case, number, special char in String

    a=input("enter word")
    d=0
    u=0
    l=0
    s=0
    for i in a:
    if i.isdigit():
    d=d+1
    elif i.isupper():
    u=u+1
    elif i.islower():
    l=l+1
    else:
    s=s+1
    print(d,u,l,s)

    ReplyDelete
  9. WAP to reverse a string in words

    a=input("enter words")
    l=a.split(" ")
    l=l[::-1]
    s=""
    for i in l:
    s=s+i+" "
    print(s)

    ReplyDelete
  10. #password strenght
    s=input("enter password")
    c=0
    for i in range(0,len(s)):
    if ord(s[i])>=48 and ord(s[i])<=57:
    c=c+1
    if ord(s[i])>=65 and ord(s[i])<=90:
    c=c+1
    if ord(s[i])>=97 and ord(s[i])<=122:
    c=c+1
    if ord(s[i])>=58 and ord(s[i])<=64:
    c=c+1
    if c>15:
    print("strong password")
    if c>=10 and c<=15:
    print("medium password")
    if c>6 and c<10:
    print("weak password")
    if c<6:
    print("password should be greater than 6 character")








    ReplyDelete
  11. x=input("enter mobile number")
    c=0
    for i in range(0,len(x)):
    if ord(x[i])>=48 and ord(x[i])<=57:
    c=c+1
    if c==10:
    print("valid mobile number")
    else:
    print("invalid mobile no")

    ReplyDelete
  12. fn=input("enter user name")
    ln=input("enter your last name")
    for i in range(0,len(fn)):
    if (ord(fn[i])>=65 and ord(fn[i])<=90) or (ord(fn[i])>=97 and ord(fn[i])<=122):
    print("valid first name")
    break;
    else:
    print("invalid first name")
    break;
    for j in range(0,len(ln)):
    if (ord(ln[j])>=65 and ord(ln[j])<=90) or (ord(ln[j])>=97 and ord(ln[j])<=122):
    print("valid last name")
    break;
    else:
    print("invalid last name")
    break;

    ReplyDelete
  13. #max in string
    s=input("enter a string")
    m="0"
    for i in s:
    if m<i:
    m=i
    print(m)

    ReplyDelete
  14. replace space with @
    x="gourav ji"
    m=' '
    for i in range(len(x)):
    if (x[i])==' ':
    m=m+'@'
    else:
    m=m+x[i]
    print(m)

    ReplyDelete
  15. How to remove all duplicates from a given string?


    st="mangalam"
    i=0
    c=''
    for data in st:
    if st.index(data)==i:
    c=c+data
    i=i+1

    print(c)

    ReplyDelete
  16. """5) How to check if two strings are rotations of each other? (solution)
    Write an efficient program to test if two given String is a rotation of each other or not, e.g. if the given String is "XYZ" and "ZXY" then your function should return true, but if the input is "XYZ" and "YXZ" then return false.
    """

    def check_rotation(str1,str2):
    if str1[-1]+str1[0:len(str1)-1]==str2:
    return True
    else:
    return False

    str1="ABCDEF"
    str2="FABCDE"

    print(check_rotation(str1,str2))

    ReplyDelete

POST Answer of Questions and ASK to Doubt