lavish
lavish

Reputation: 43

Index of a character in a string

I am trying to find out the index of a specific character in a string.For example:

MyString:abfkjgck
Text:afgf

I want to find the index of each character of text in MyString.This is what have tried:

a=string.ascii_uppercase
t=input("Enter the plain text :")
d=t[0]
x=a.index(d)
print(x)

I keep getting a Value error.

Upvotes: 0

Views: 110

Answers (1)

John1024
John1024

Reputation: 113984

Try:

a=string.ascii_uppercase
t=input("Enter the plain text :")
x=[a.index(d.upper()) for d in t]
print(x)

Sample output:

Enter the plain text :afgf
[0, 5, 6, 5]

Discussion:

Consider why this code can generate a ValueError:

a=string.ascii_uppercase
t=input("Enter the plain text :")
d=t[0]
x=a.index(d)
print(x)

A ValueError occurs if d is not found in a. Note that s consists only of upper case ASCII letters. Consequently, it does not contain any lower case letters. If the user enters a lower case letter, a ValueError message will result.

This was eliminated in the suggested code above by using d.upper() in place of just d.

Also, to gather the indices of all the characters typed by the user instead of just the first, a list comprehension can be used: x=[a.index(d.upper()) for d in t].

Ignoring spaces

Suppose that we want to ignore any spaces that the user enters:

import string
a=string.ascii_uppercase
t=input("Enter the plain text :")
x=[a.index(d.upper()) for d in t if d != " "]
print(x)

Gracefully handling non-alphabetic characters

In this code, any space or other non-alphabetic character is assigned the value of -1:

import string
a=string.ascii_uppercase
t=input("Enter the plain text :")
x=[a.find(d.upper()) for d in t]
print(x)

Example:

Enter the plain text :a#b% c
[0, -1, 1, -1, -1, 2]

Upvotes: 1

Related Questions