Поиск буквы в строке python

How to get the position of a character in Python?

There are two string methods for this, find() and index() . The difference between the two is what happens when the search string isn’t found. find() returns -1 and index() raises a ValueError .

Using find()

>>> myString = 'Position of a character' >>> myString.find('s') 2 >>> myString.find('x') -1 

Using index()

>>> myString = 'Position of a character' >>> myString.index('s') 2 >>> myString.index('x') Traceback (most recent call last): File "", line 1, in ValueError: substring not found 

From the Python manual

string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end] . Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

string.index(s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.

Just for a sake of completeness, if you need to find all positions of a character in a string, you can do the following:

s = 'shak#spea#e' c = '#' print([pos for pos, char in enumerate(s) if char == c]) 

foo = ( [pos for pos, char in enumerate(s) if char == c]) will put the coordinates foo in a list format. I find this really helpful

>>> s="mystring" >>> s.index("r") 4 >>> s.find("r") 4 
>>> for i,c in enumerate(s): . if "r"==c: print i . 4 

s.search() raises a ValueError when the substring is not found. s.find() returns -1 if the substring isn’t found.

Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last ‘.’, in this case use rfind:

path = 'toto.titi.tata..xls' path.find('.') 4 path.rfind('.') 15 

in my case, I use the following, which works whatever the complete file name is:

filename_without_extension = complete_name[:complete_name.rfind('.')] 

This is helpful for finding the extent of a string. For example, finding a dictionary could be: left = q.find(«<"); right = q.rfind(">«) .

If you’re trying to find the extension of a filename, the better way to do it now would probably be with Pathlib. from pathlib import Path; p = Path(«toto.titi.tata..xls») . Then p.suffix == «.xls» and p.stem == «toto.titi.tata.»

What happens when the string contains a duplicate character? from my experience with index() I saw that for duplicate you get back the same index.

s = 'abccde' for c in s: print('%s, %d' % (c, s.index(c))) 

In that case you can do something like that:

for i, character in enumerate(my_string): # i is the position of the character in the string 
string.find(character) string.index(character) 

Perhaps you’d like to have a look at the documentation to find out what the difference between the two is.

Читайте также:  List all css selectors

From that linked documentation: s.search() raises a ValueError when the substring is not found. s.find() returns -1 if the substring isn’t found.

A character might appear multiple times in a string. For example in a string sentence , position of e is 1, 4, 7 (because indexing usually starts from zero). but what I find is both of the functions find() and index() returns first position of a character. So, this can be solved doing this:

def charposition(string, char): pos = [] #list to store positions for each 'char' in 'string' for n in range(len(string)): if string[n] == char: pos.append(n) return pos s = "sentence" print(charposition(s, 'e')) #Output: [1, 4, 7] 

If you want to find the first match.

Python has a in-built string method that does the work: index().

string.index(value, start, end) 
  • Value: (Required) The value to search for.
  • start: (Optional) Where to start the search. Default is 0.
  • end: (Optional) Where to end the search. Default is to the end of the string.
def character_index(): string = "Hello World! This is an example sentence with no meaning." match = "i" return string.index(match) print(character_index()) > 15 

If you want to find all the matches.

Let’s say you need all the indexes where the character match is and not just the first one.

The pythonic way would be to use enumerate() .

def character_indexes(): string = "Hello World! This is an example sentence with no meaning." match = "i" indexes_of_match = [] for index, character in enumerate(string): if character == match: indexes_of_match.append(index) return indexes_of_match print(character_indexes()) # [15, 18, 42, 53] 

Or even better with a list comprehension:

def character_indexes_comprehension(): string = "Hello World! This is an example sentence with no meaning." match = "i" return [index for index, character in enumerate(string) if character == match] print(character_indexes_comprehension()) # [15, 18, 42, 53] 

Источник

Python find() – How to Search for a Substring in a String

Dionysia Lemonaki

Dionysia Lemonaki

Python find() – How to Search for a Substring in a String

When you’re working with a Python program, you might need to search for and locate a specific string inside another string.

This is where Python’s built-in string methods come in handy.

In this article, you will learn how to use Python’s built-in find() string method to help you search for a substring inside a string.

Here is what we will cover:

The find() Method — A Syntax Overview

The find() string method is built into Python’s standard library.

It takes a substring as input and finds its index — that is, the position of the substring inside the string you call the method on.

The general syntax for the find() method looks something like this:

string_object.find("substring", start_index_number, end_index_number) 
  • string_object is the original string you are working with and the string you will call the find() method on. This could be any word you want to search through.
  • The find() method takes three parameters – one required and two optional.
  • «substring» is the first required parameter. This is the substring you are trying to find inside string_object . Make sure to include quotation marks.
  • start_index_number is the second parameter and it’s optional. It specifies the starting index and the position from which the search will start. The default value is 0 .
  • end_index_number is the third parameter and it’s also optional. It specifies the end index and where the search will stop. The default is the length of the string.
  • Both the start_index_number and the end_index_number specify the range over which the search will take place and they narrow the search down to a particular section.
Читайте также:  Python array delete element by value

The return value of the find() method is an integer value.

If the substring is present in the string, find() returns the index, or the character position, of the first occurrence of the specified substring from that given string.

If the substring you are searching for is not present in the string, then find() will return -1 . It will not throw an exception.

How to Use find() with No Start and End Parameters Example

The following examples illustrate how to use the find() method using the only required parameter – the substring you want to search.

You can take a single word and search to find the index number of a specific letter:

fave_phrase = "Hello world!" # find the index of the letter 'w' search_fave_phrase = fave_phrase.find("w") print(search_fave_phrase) #output # 6 

I created a variable named fave_phrase and stored the string Hello world! .

I called the find() method on the variable containing the string and searched for the letter ‘w’ inside Hello world! .

I stored the result of the operation in a variable named search_fave_phrase and then printed its contents to the console.

The return value was the index of w which in this case was the integer 6 .

Keep in mind that indexing in programming and Computer Science in general always starts at 0 and not 1 .

How to Use find() with Start and End Parameters Example

Using the start and end parameters with the find() method lets you limit your search.

For example, if you wanted to find the index of the letter ‘w’ and start the search from position 3 and not earlier, you would do the following:

fave_phrase = "Hello world!" # find the index of the letter 'w' starting from position 3 search_fave_phrase = fave_phrase.find("w",3) print(search_fave_phrase) #output # 6 

Since the search starts at position 3, the return value will be the first instance of the string containing ‘w’ from that position and onwards.

You can also narrow down the search even more and be more specific with your search with the end parameter:

fave_phrase = "Hello world!" # find the index of the letter 'w' between the positions 3 and 8 search_fave_phrase = fave_phrase.find("w",3,8) print(search_fave_phrase) #output # 6 

Substring Not Found Example

As mentioned earlier, if the substring you specify with find() is not present in the string, then the output will be -1 and not an exception.

fave_phrase = "Hello world!" # search for the index of the letter 'a' in "Hello world" search_fave_phrase = fave_phrase.find("a") print(search_fave_phrase) # -1 

Is the find() Method Case-Sensitive?

What happens if you search for a letter in a different case?

fave_phrase = "Hello world!" #search for the index of the letter 'W' capitalized search_fave_phrase = fave_phrase.find("W") print(search_fave_phrase) #output # -1 

In an earlier example, I searched for the index of the letter w in the phrase «Hello world!» and the find() method returned its position.

Читайте также:  Способы аутентификации java ee

In this case, searching for the letter W capitalized returns -1 – meaning the letter is not present in the string.

So, when searching for a substring with the find() method, remember that the search will be case-sensitive.

The find() Method vs the in Keyword – What’s the Difference?

Use the in keyword to check if the substring is present in the string in the first place.

The general syntax for the in keyword is the following:

The in keyword returns a Boolean value – a value that is either True or False .

The in operator returns True when the substring is present in the string.

And if the substring is not present, it returns False :

Using the in keyword is a helpful first step before using the find() method.

You first check to see if a string contains a substring, and then you can use find() to find the position of the substring. That way, you know for sure that the substring is present.

So, use find() to find the index position of a substring inside a string and not to look if the substring is present in the string.

The find() Method vs the index() Method – What’s the Difference?

Similar to the find() method, the index() method is a string method used for finding the index of a substring inside a string.

So, both methods work in the same way.

The difference between the two methods is that the index() method raises an exception when the substring is not present in the string, in contrast to the find() method that returns the -1 value.

fave_phrase = "Hello world!" # search for the index of the letter 'a' in 'Hello world!' search_fave_phrase = fave_phrase.index("a") print(search_fave_phrase) #output # Traceback (most recent call last): # File "/Users/dionysialemonaki/python_article/demopython.py", line 4, in # search_fave_phrase = fave_phrase.index("a") # ValueError: substring not found 

The example above shows that index() throws a ValueError when the substring is not present.

You may want to use find() over index() when you don’t want to deal with catching and handling any exceptions in your programs.

Conclusion

And there you have it! You now know how to search for a substring in a string using the find() method.

I hope you found this tutorial helpful.

To learn more about the Python programming language, check out freeCodeCamp’s Python certification.

You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce your understanding of the concepts you learned.

Thank you for reading, and happy coding!

Источник

Оцените статью