How to Get the Position of a Character in Python

How do I get the position of a string inside a list in Python?

This code of yours is messed up a bit


space = ' ' # This is fine but redundant
for space in sentence: # Shouldn't reuse variable names. Should be <for char in sentence. But I wouldn't use that either since we don't need the char it self but the index
if space in sentence: #Should be <if char == space> Your just returns a True if there's a single space anywhere in the string. Assuming it's using the correct variable named space. Honestly I don't know what this code will do since I didn't run it :P
space_position = sentence[space]
print(space_position)

Here's what I would do, which could be done better since I'm a beginner too.

sentence = input('Please type a sentence: ')

for i in range(len(sentence)):
if sentence[i] == " ":
print(i)

#>>>Please type a sentence: A sentence and spaces
#>>>1
#>>>10
#>>>14

Get character position in alphabet

It is called index. For e.g.

>>> import string
>>> string.lowercase.index('b')
1
>>>

Note: in Python 3, string.lowercase has been renamed to string.ascii_lowercase.

How to get position of each character on a string without using find function

Your code it's basically right. The problem is that you're just saying in your code that, if the coincidence is found between the string and the token, then return the position e, finishing there the for loop.

Thus, to avoid your problem, you only need to add an empty string at the begining of your function (result = []) and, when a coincidence is found, append this position to the result list. Finally, once the for loop is finished, ask your function to return result

This should work:

#eg: find("Pythhon","h")
#needed output: [3,4] (the positions of each occurrence)
#instead the output is showing: [3] (position)
def find(string, token):
#start at index 0
result = []
for e in range(0,len(string)):
#compare each character to token
if string[e] == token:
#if true return the position of occurences
result.append(e)
return result

Python: split a string by the position of a character

You can do this with strings (and lists) using slicing:

string = "hello world!"
splitat = 4
left, right = string[:splitat], string[splitat:]

will result in:

>>> left
hell
>>> right
o world!

get index of character in python list

>>> ['a', 'b'].index('b')
1

If the list is already sorted, you can of course do better than linear search.



Related Topics



Leave a reply



Submit