Computer Science, asked by spygirl6, 3 months ago

write the PYTHON SCRIPT to accept a string and a character and display each location where the character is present within the string...can you give the python script for this question??​

Answers

Answered by lalitnit
1

Method #1: Using Naive Method

# Python3 code to demonstrate

# to find the first position of the character

# in a given string

# Initialising string

ini_string = 'abcdef'

# Character to find

c = "b"

# printing initial string and character

print ("initial_string : ", ini_string, "\ncharacter_to_find : ", c)

# Using Naive Method

res = None

for i in range(0, len(ini_string)):

if ini_string[i] == c:

res = i + 1

break

if res == None:

print ("No such charater available in string")

else:

print ("Character {} is present at {}".format(c, str(res)))

Output:

initial_string : abcdef

character_to_find : b

Character b is present at 2

Method #2: Using find

This method returns -1 in case character not present.

# Python3 code to demonstrate

# to find first position of character

# in a given string

# Initialising string

ini_string = 'abcdef'

ini_string2 = 'xyze'

# Character to find

c = "b"

# printing initial string and character

print ("initial_strings : ", ini_string, " ",

ini_string2, "\ncharacter_to_find : ", c)

# Using find Method

res1 = ini_string.find(c)

res2 = ini_string2.find(c)

if res1 == -1:

print ("No such charater available in string {}".

format(ini_string))

else:

print ("Character {} in string {} is present at {}".

format(c, ini_string, str(res1 + 1)))

if res2 == -1:

print ("No such charater available in string {}".format(

ini_string2))

else:

print ("Character {} in string {} is present at {}".format(

c, ini_string2, str(res2 + 1)))

Output:

initial_strings : abcdef xyze

character_to_find : b

Character b in string abcdef is present at 2

No such charater available in string xyze

Similar questions