Как найти определенные символы в строке python

Часто нам нужно найти символ в строке python. Для решения этой задачи разработчики используют метод find(). Он помогает найти индекс первого совпадения подстроки в строке. Если символ или подстрока не найдены, find возвращает -1.

Синтаксис

string.find(substring,start,end)

Метод find принимает три параметра:

  • substring (символ/подстрока) — подстрока, которую нужно найти в данной строке.
  • start (необязательный) — первый индекс, с которого нужно начинать поиск. По умолчанию значение равно 0.
  • end (необязательный) — индекс, на котором нужно закончить поиск. По умолчанию равно длине строки.

Параметры, которые передаются в метод, — это подстрока, которую требуются найти, индекс начала и конца поиска. Значение по умолчанию для начала поиска — 0, а для конца — длина строки.

В этом примере используем метод со значениями по умолчанию.

Метод find() будет искать символ и вернет положение первого совпадения. Даже если символ встречается несколько раз, то метод вернет только положение первого совпадения.


>>> string = "Добро пожаловать!"
>>> print("Индекс первой буквы 'о':", string.find("о"))
Индекс первой буквы 'о': 1

Поиск не с начала строки с аргументом start

Можно искать подстроку, указав также начальное положение поиска.

В этом примере обозначим стартовое положение значением 8 и метод начнет искать с символа с индексом 8. Последним положением будет длина строки — таким образом метод выполнит поиска с индекса 8 до окончания строки.


>>> string = "Специалисты назвали плюсы и минусы Python"
>>> print("Индекс подстроки 'али' без учета первых 8 символов:", string.find("али", 8))
Индекс подстроки 'али' без учета первых 8 символов: 16

Поиск символа в подстроке со start и end

С помощью обоих аргументов (start и end) можно ограничить поиск и не проводить его по всей строке. Найдем индексы слова «пожаловать» и повторим поиск по букве «о».


>>> string = "Добро пожаловать!"
>>> start = string.find("п")
>>> end = string.find("ь") + 1
>>> print("Индекс первой буквы 'о' в подстроке:", string.find("о", start, end))
Индекс первой буквы 'о' в подстроке: 7

Проверка есть ли символ в строке

Мы знаем, что метод find() позволяет найти индекс первого совпадения подстроки. Он возвращает -1 в том случае, если подстрока не была найдена.


>>> string = "Добро пожаловать!"
>>> print("Есть буква 'г'?", string.find("г") != -1)
Есть буква 'г'? False
>>> print("Есть буква 'т'?", string.find("т") != -1)
Есть буква 'т'? True

Поиск последнего вхождения символа в строку

Функция rfind() напоминает find(), а единое отличие в том, что она возвращает максимальный индекс. В обоих случаях же вернется -1, если подстрока не была найдена.

В следующем примере есть строка «Добро пожаловать!». Попробуем найти в ней символ «о» с помощью методов find() и rfind().


>>> string = "Добро пожаловать"
>>> print("Поиск 'о' методом find:", string.find("о"))
Поиск 'о' методом find: 1
>>> print("Поиск 'о' методом rfind:", string.rfind("о"))
Поиск 'о' методом rfind: 11

Вывод показывает, что find() возвращает индекс первого совпадения подстроки, а rfind() — последнего совпадения.

Второй способ поиска — index()

Метод index() помогает найти положение данной подстроки по аналогии с find(). Единственное отличие в том, что index() бросит исключение в том случае, если подстрока не будет найдена, а find() просто вернет -1.

Вот рабочий пример, показывающий разницу в поведении index() и find():


>>> string = "Добро пожаловать"
>>> print("Поиск 'о' методом find:", string.find("о"))
Поиск 'о' методом find: 1
>>> print("Поиск 'о' методом index:", string.index("о"))
Поиск 'о' методом index: 1

В обоих случаях возвращается одна и та же позиция. А теперь попробуем с подстрокой, которой нет в строке:


>>> string = "Добро пожаловать"
>>> print("Поиск 'г' методом find:", string.find("г"))
Поиск 'г' методом find: 1
>>> print("Поиск 'г' методом index:", string.index("г"))
Traceback (most recent call last):
File "pyshell#21", line 1, in module
print("Поиск 'г' методом index:", string.index("г"))
ValueError: substring not found

В этом примере мы пытались найти подстроку «г». Ее там нет, поэтому find() возвращает -1, а index() бросает исключение.

Поиск всех вхождений символа в строку

Чтобы найти общее количество совпадений подстроки в строке можно использовать ту же функцию find(). Пройдемся циклом while по строке и будем задействовать параметр start из метода find().

Изначально переменная start будет равна -1, что бы прибавлять 1 у каждому новому поиску и начать с 0. Внутри цикла проверяем, присутствует ли подстрока в строке с помощью метода find.

Если вернувшееся значение не равно -1, то обновляем значением count.

Вот рабочий пример:


my_string = "Добро пожаловать"
start = -1
count = 0

while True:
start = my_string.find("о", start+1)
if start == -1:
break
count += 1

print("Количество вхождений символа в строку: ", count )

Количество вхождений символа в строку:  4

Выводы

  • Метод find() помогает найти индекс первого совпадения подстроки в данной строке. Возвращает -1, если подстрока не была найдена.
  • В метод передаются три параметра: подстрока, которую нужно найти, start со значением по умолчанию равным 0 и end со значением по умолчанию равным длине строки.
  • Можно искать подстроку в данной строке, задав начальное положение, с которого следует начинать поиск.
  • С помощью параметров start и end можно ограничить зону поиска, чтобы не выполнять его по всей строке.
  • Функция rfind() повторяет возможности find(), но возвращает максимальный индекс (то есть, место последнего совпадения). В обоих случаях возвращается -1, если подстрока не была найдена.
  • index() — еще одна функция, которая возвращает положение подстроки. Отличие лишь в том, что index() бросает исключение, если подстрока не была найдена, а find() возвращает -1.
  • find() можно использовать в том числе и для поиска общего числа совпадений подстроки.

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:

  1. Syntax of the find() method
    1. How to use find() with no start and end parameters example
    2. How to use find() with start and end parameters example
    3. Substring not found example
    4. Is the find() method case-sensitive?
  2. find() vs in keyword
  3. find() vs index()

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)

Let’s break it down:

  • 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.

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.

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:

substring in string

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

>>> "w" in "Hello world!"
True

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

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

>>> "a" in "Hello world!"
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 <module>
#    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!

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How can I get the position of a character inside a string in Python?

bad_coder's user avatar

bad_coder

10.9k20 gold badges42 silver badges70 bronze badges

asked Feb 19, 2010 at 6:32

user244470's user avatar

0

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 "<stdin>", line 1, in <module>
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.

And:

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

Tomerikoo's user avatar

Tomerikoo

18.1k16 gold badges45 silver badges60 bronze badges

answered Feb 19, 2010 at 6:35

Eli Bendersky's user avatar

Eli BenderskyEli Bendersky

261k88 gold badges350 silver badges412 bronze badges

1

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])

which will print: [4, 9]

Jolbas's user avatar

Jolbas

7475 silver badges15 bronze badges

answered Sep 26, 2015 at 7:59

Salvador Dali's user avatar

Salvador DaliSalvador Dali

212k146 gold badges696 silver badges752 bronze badges

2

>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4

«Long winded» way

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

to get substring,

>>> s="mystring"
>>> s[4:10]
'ring'

answered Feb 19, 2010 at 6:36

ghostdog74's user avatar

ghostdog74ghostdog74

325k56 gold badges257 silver badges342 bronze badges

4

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('.')]

answered Sep 28, 2017 at 6:37

A.Joly's user avatar

A.JolyA.Joly

2,2772 gold badges20 silver badges24 bronze badges

2

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.

For example:

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

would return:

a, 0
b, 1
c, 2
c, 2
d, 4

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

Martin Tournoij's user avatar

answered Jul 1, 2015 at 12:40

DimSarak's user avatar

DimSarakDimSarak

4522 gold badges5 silver badges11 bronze badges

1

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.

Brad Koch's user avatar

Brad Koch

19k19 gold badges107 silver badges137 bronze badges

answered Feb 19, 2010 at 6:37

John Machin's user avatar

John MachinJohn Machin

80.9k11 gold badges141 silver badges187 bronze badges

1

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]

answered Sep 16, 2018 at 9:33

itssubas's user avatar

itssubasitssubas

1632 silver badges11 bronze badges

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)

Where:

  • 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]

answered Jan 26, 2021 at 5:01

Guzman Ojero's user avatar

Guzman OjeroGuzman Ojero

2,6621 gold badge19 silver badges20 bronze badges

2

more_itertools.locate is a third-party tool that finds all indicies of items that satisfy a condition.

Here we find all index locations of the letter "i".

Given

import more_itertools as mit


text = "supercalifragilisticexpialidocious"
search = lambda x: x == "i"

Code

list(mit.locate(text, search))
# [8, 13, 15, 18, 23, 26, 30]

answered Feb 9, 2018 at 0:46

pylang's user avatar

pylangpylang

39.8k11 gold badges127 silver badges120 bronze badges

Most methods I found refer to finding the first substring in a string. To find all the substrings, you need to work around.

For example:

Define the string

vars = ‘iloveyoutosimidaandilikeyou’

Define the substring

key = 'you'

Define a function that can find the location for all the substrings within the string

def find_all_loc(vars, key):

    pos = []
    start = 0
    end = len(vars)

    while True: 
        loc = vars.find(key, start, end)
        if  loc is -1:
            break
        else:
            pos.append(loc)
            start = loc + len(key)
            
    return pos

pos = find_all_loc(vars, key)

print(pos)
[5, 24]

Emi OB's user avatar

Emi OB

2,7943 gold badges13 silver badges28 bronze badges

answered Nov 5, 2021 at 8:44

Chan Kin Sung's user avatar

0

A solution with numpy for quick access to all indexes:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')

answered Jan 15, 2020 at 20:40

Seb's user avatar

SebSeb

3024 silver badges6 bronze badges

2

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Check if a Python String Contains a Substring

If you’re new to programming or come from a programming language other than Python, you may be looking for the best way to check whether a string contains another string in Python.

Identifying such substrings comes in handy when you’re working with text content from a file or after you’ve received user input. You may want to perform different actions in your program depending on whether a substring is present or not.

In this tutorial, you’ll focus on the most Pythonic way to tackle this task, using the membership operator in. Additionally, you’ll learn how to identify the right string methods for related, but different, use cases.

Finally, you’ll also learn how to find substrings in pandas columns. This is helpful if you need to search through data from a CSV file. You could use the approach that you’ll learn in the next section, but if you’re working with tabular data, it’s best to load the data into a pandas DataFrame and search for substrings in pandas.

How to Confirm That a Python String Contains Another String

If you need to check whether a string contains a substring, use Python’s membership operator in. In Python, this is the recommended way to confirm the existence of a substring in a string:

>>>

>>> raw_file_content = """Hi there and welcome.
... This is a special hidden file with a SECRET secret.
... I don't want to tell you The Secret,
... but I do want to secretly tell you that I have one."""

>>> "secret" in raw_file_content
True

The in membership operator gives you a quick and readable way to check whether a substring is present in a string. You may notice that the line of code almost reads like English.

When you use in, the expression returns a Boolean value:

  • True if Python found the substring
  • False if Python didn’t find the substring

You can use this intuitive syntax in conditional statements to make decisions in your code:

>>>

>>> if "secret" in raw_file_content:
...    print("Found!")
...
Found!

In this code snippet, you use the membership operator to check whether "secret" is a substring of raw_file_content. If it is, then you’ll print a message to the terminal. Any indented code will only execute if the Python string that you’re checking contains the substring that you provide.

The membership operator in is your best friend if you just need to check whether a Python string contains a substring.

However, what if you want to know more about the substring? If you read through the text stored in raw_file_content, then you’ll notice that the substring occurs more than once, and even in different variations!

Which of these occurrences did Python find? Does capitalization make a difference? How often does the substring show up in the text? And what’s the location of these substrings? If you need the answer to any of these questions, then keep on reading.

Generalize Your Check by Removing Case Sensitivity

Python strings are case sensitive. If the substring that you provide uses different capitalization than the same word in your text, then Python won’t find it. For example, if you check for the lowercase word "secret" on a title-case version of the original text, the membership operator check returns False:

>>>

>>> title_cased_file_content = """Hi There And Welcome.
... This Is A Special Hidden File With A Secret Secret.
... I Don't Want To Tell You The Secret,
... But I Do Want To Secretly Tell You That I Have One."""

>>> "secret" in title_cased_file_content
False

Despite the fact that the word secret appears multiple times in the title-case text title_cased_file_content, it never shows up in all lowercase. That’s why the check that you perform with the membership operator returns False. Python can’t find the all-lowercase string "secret" in the provided text.

Humans have a different approach to language than computers do. This is why you’ll often want to disregard capitalization when you check whether a string contains a substring in Python.

You can generalize your substring check by converting the whole input text to lowercase:

>>>

>>> file_content = title_cased_file_content.lower()

>>> print(file_content)
hi there and welcome.
this is a special hidden file with a secret secret.
i don't want to tell you the secret,
but i do want to secretly tell you that i have one.

>>> "secret" in file_content
True

Converting your input text to lowercase is a common way to account for the fact that humans think of words that only differ in capitalization as the same word, while computers don’t.

Now that you’ve converted the string to lowercase to avoid unintended issues stemming from case sensitivity, it’s time to dig further and learn more about the substring.

Learn More About the Substring

The membership operator in is a great way to descriptively check whether there’s a substring in a string, but it doesn’t give you any more information than that. It’s perfect for conditional checks—but what if you need to know more about the substrings?

Python provides many additonal string methods that allow you to check how many target substrings the string contains, to search for substrings according to elaborate conditions, or to locate the index of the substring in your text.

In this section, you’ll cover some additional string methods that can help you learn more about the substring.

By using in, you confirmed that the string contains the substring. But you didn’t get any information on where the substring is located.

If you need to know where in your string the substring occurs, then you can use .index() on the string object:

>>>

>>> file_content = """hi there and welcome.
... this is a special hidden file with a secret secret.
... i don't want to tell you the secret,
... but i do want to secretly tell you that i have one."""

>>> file_content.index("secret")
59

When you call .index() on the string and pass it the substring as an argument, you get the index position of the first character of the first occurrence of the substring.

But what if you want to find other occurrences of the substring? The .index() method also takes a second argument that can define at which index position to start looking. By passing specific index positions, you can therefore skip over occurrences of the substring that you’ve already identified:

>>>

>>> file_content.index("secret", 60)
66

When you pass a starting index that’s past the first occurrence of the substring, then Python searches starting from there. In this case, you get another match and not a ValueError.

That means that the text contains the substring more than once. But how often is it in there?

You can use .count() to get your answer quickly using descriptive and idiomatic Python code:

>>>

>>> file_content.count("secret")
4

You used .count() on the lowercase string and passed the substring "secret" as an argument. Python counted how often the substring appears in the string and returned the answer. The text contains the substring four times. But what do these substrings look like?

You can inspect all the substrings by splitting your text at default word borders and printing the words to your terminal using a for loop:

>>>

>>> for word in file_content.split():
...    if "secret" in word:
...        print(word)
...
secret
secret.
secret,
secretly

In this example, you use .split() to separate the text at whitespaces into strings, which Python packs into a list. Then you iterate over this list and use in on each of these strings to see whether it contains the substring "secret".

Now that you can inspect all the substrings that Python identifies, you may notice that Python doesn’t care whether there are any characters after the substring "secret" or not. It finds the word whether it’s followed by whitespace or punctuation. It even finds words such as "secretly".

That’s good to know, but what can you do if you want to place stricter conditions on your substring check?

Find a Substring With Conditions Using Regex

You may only want to match occurrences of your substring followed by punctuation, or identify words that contain the substring plus other letters, such as "secretly".

For such cases that require more involved string matching, you can use regular expressions, or regex, with Python’s re module.

For example, if you want to find all the words that start with "secret" but are then followed by at least one additional letter, then you can use the regex word character (w) followed by the plus quantifier (+):

>>>

>>> import re

>>> file_content = """hi there and welcome.
... this is a special hidden file with a secret secret.
... i don't want to tell you the secret,
... but i do want to secretly tell you that i have one."""

>>> re.search(r"secretw+", file_content)
<re.Match object; span=(128, 136), match='secretly'>

The re.search() function returns both the substring that matched the condition as well as its start and end index positions—rather than just True!

You can then access these attributes through methods on the Match object, which is denoted by m:

>>>

>>> m = re.search(r"secretw+", file_content)

>>> m.group()
'secretly'

>>> m.span()
(128, 136)

These results give you a lot of flexibility to continue working with the matched substring.

For example, you could search for only the substrings that are followed by a comma (,) or a period (.):

>>>

>>> re.search(r"secret[.,]", file_content)
<re.Match object; span=(66, 73), match='secret.'>

There are two potential matches in your text, but you only matched the first result fitting your query. When you use re.search(), Python again finds only the first match. What if you wanted all the mentions of "secret" that fit a certain condition?

To find all the matches using re, you can work with re.findall():

>>>

>>> re.findall(r"secret[.,]", file_content)
['secret.', 'secret,']

By using re.findall(), you can find all the matches of the pattern in your text. Python saves all the matches as strings in a list for you.

When you use a capturing group, you can specify which part of the match you want to keep in your list by wrapping that part in parentheses:

>>>

>>> re.findall(r"(secret)[.,]", file_content)
['secret', 'secret']

By wrapping secret in parentheses, you defined a single capturing group. The findall() function returns a list of strings matching that capturing group, as long as there’s exactly one capturing group in the pattern. By adding the parentheses around secret, you managed to get rid of the punctuation!

Using re.findall() with match groups is a powerful way to extract substrings from your text. But you only get a list of strings, which means that you’ve lost the index positions that you had access to when you were using re.search().

If you want to keep that information around, then re can give you all the matches in an iterator:

>>>

>>> for match in re.finditer(r"(secret)[.,]", file_content):
...    print(match)
...
<re.Match object; span=(66, 73), match='secret.'>
<re.Match object; span=(103, 110), match='secret,'>

When you use re.finditer() and pass it a search pattern and your text content as arguments, you can access each Match object that contains the substring, as well as its start and end index positions.

You may notice that the punctuation shows up in these results even though you’re still using the capturing group. That’s because the string representation of a Match object displays the whole match rather than just the first capturing group.

But the Match object is a powerful container of information and, like you’ve seen earlier, you can pick out just the information that you need:

>>>

>>> for match in re.finditer(r"(secret)[.,]", file_content):
...    print(match.group(1))
...
secret
secret

By calling .group() and specifying that you want the first capturing group, you picked the word secret without the punctuation from each matched substring.

You can go into much more detail with your substring matching when you use regular expressions. Instead of just checking whether a string contains another string, you can search for substrings according to elaborate conditions.

Using regular expressions with re is a good approach if you need information about the substrings, or if you need to continue working with them after you’ve found them in the text. But what if you’re working with tabular data? For that, you’ll turn to pandas.

Find a Substring in a pandas DataFrame Column

If you work with data that doesn’t come from a plain text file or from user input, but from a CSV file or an Excel sheet, then you could use the same approach as discussed above.

However, there’s a better way to identify which cells in a column contain a substring: you’ll use pandas! In this example, you’ll work with a CSV file that contains fake company names and slogans. You can download the file below if you want to work along:

When you’re working with tabular data in Python, it’s usually best to load it into a pandas DataFrame first:

>>>

>>> import pandas as pd

>>> companies = pd.read_csv("companies.csv")

>>> companies.shape
(1000, 2)

>>> companies.head()
             company                                     slogan
0      Kuvalis-Nolan      revolutionize next-generation metrics
1  Dietrich-Champlin  envisioneer bleeding-edge functionalities
2           West Inc            mesh user-centric infomediaries
3         Wehner LLC               utilize sticky infomediaries
4      Langworth Inc                 reinvent magnetic networks

In this code block, you loaded a CSV file that contains one thousand rows of fake company data into a pandas DataFrame and inspected the first five rows using .head().

After you’ve loaded the data into the DataFrame, you can quickly query the whole pandas column to filter for entries that contain a substring:

>>>

>>> companies[companies.slogan.str.contains("secret")]
              company                                  slogan
7          Maggio LLC                    target secret niches
117      Kub and Sons              brand secret methodologies
654       Koss-Zulauf              syndicate secret paradigms
656      Bernier-Kihn  secretly synthesize back-end bandwidth
921      Ward-Shields               embrace secret e-commerce
945  Williamson Group             unleash secret action-items

You can use .str.contains() on a pandas column and pass it the substring as an argument to filter for rows that contain the substring.

When you’re working with .str.contains() and you need more complex match scenarios, you can also use regular expressions! You just need to pass a regex-compliant search pattern as the substring argument:

>>>

>>> companies[companies.slogan.str.contains(r"secretw+")]
          company                                  slogan
656  Bernier-Kihn  secretly synthesize back-end bandwidth

In this code snippet, you’ve used the same pattern that you used earlier to match only words that contain secret but then continue with one or more word character (w+). Only one of the companies in this fake dataset seems to operate secretly!

You can write any complex regex pattern and pass it to .str.contains() to carve from your pandas column just the rows that you need for your analysis.

Conclusion

Like a persistent treasure hunter, you found each "secret", no matter how well it was hidden! In the process, you learned that the best way to check whether a string contains a substring in Python is to use the in membership operator.

You also learned how to descriptively use two other string methods, which are often misused to check for substrings:

  • .count() to count the occurrences of a substring in a string
  • .index() to get the index position of the beginning of the substring

After that, you explored how to find substrings according to more advanced conditions with regular expressions and a few functions in Python’s re module.

Finally, you also learned how you can use the DataFrame method .str.contains() to check which entries in a pandas DataFrame contain a substring .

You now know how to pick the most idiomatic approach when you’re working with substrings in Python. Keep using the most descriptive method for the job, and you’ll write code that’s delightful to read and quick for others to understand.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Check if a Python String Contains a Substring

Python_Deep_5.6_site-5020-7250df.png

В этой статье поговорим про строки в Python, особенности поиска, а также о том, как искать подстроку или символ в строке.

Python_Pro_970x90-20219-1c8674.png

Но сначала давайте вспомним основные методы для обработки строк в Python:
• isalpha(str): если строка в Python включает в себя лишь алфавитные символы, возвращается True;
• islower(str): True возвращается, если строка включает лишь символы в нижнем регистре;
• isupper(str): True, если символы строки в Python находятся в верхнем регистре;
• startswith(str): True, когда строка начинается с подстроки str;
• isdigit(str): True, когда каждый символ строки — цифра;
• endswith(str): True, когда строка в Python заканчивается на подстроку str;
• upper(): строка переводится в верхний регистр;
• lower(): строка переводится в нижний регистр;
• title(): для перевода начальных символов всех слов в строке в верхний регистр;
• capitalize(): для перевода первой буквы самого первого слова строки в верхний регистр;
• lstrip(): из строки в Python удаляются начальные пробелы;
• rstrip(): из строки в Python удаляются конечные пробелы;
• strip(): из строки в Python удаляются и начальные, и конечные пробелы;
• rjust(width): когда длина строки меньше, чем параметр width, слева добавляются пробелы, строка выравнивается по правому краю;
• ljust(width): когда длина строки в Python меньше, чем параметр width, справа от неё добавляются пробелы для дополнения значения width, при этом происходит выравнивание строки по левому краю;
• find(str[, start [, end]): происходит возвращение индекса подстроки в строку в Python. В том случае, если подстрока не найдена, выполняется возвращение числа -1;
• center(width): когда длина строки в Python меньше, чем параметр width, слева и справа добавляются пробелы (равномерно) для дополнения значения width, причём происходит выравнивание строки по центру;
• split([delimeter[, num]]): строку в Python разбиваем на подстроки в зависимости от разделителя;
• replace(old, new[, num]): в строке одна подстрока меняется на другую;
• join(strs): строки объединяются в одну строку, между ними вставляется определённый разделитель.

Обрабатываем строку в Python

Представим, что ожидается ввод числа с клавиатуры. Перед преобразованием введенной нами строки в число можно легко проверить, введено ли действительно число. Если это так, выполнится операция преобразования. Для обработки строки используем такой метод в Python, как isnumeric():

string = input("Введите какое-нибудь число: ")
if string.isnumeric():
    number = int(string)
    print(number)

Следующий пример позволяет удалять пробелы в конце и начале строки:

string = "   привет мир!  "
string = string.strip()
print(string)           # привет мир!

Так можно дополнить строку пробелами и выполнить выравнивание:

print("iPhone 7:", "52000".rjust(10))
print("Huawei P10:", "36000".rjust(10))

В консоли Python будет выведено следующее:

iPhone 7:      52000
Huawei P10:      36000

Поиск подстроки в строке

Чтобы в Python выполнить поиск в строке, используют метод find(). Он имеет три формы и возвращает индекс 1-го вхождения подстроки в строку:
• find(str): поиск подстроки str производится с начала строки и до её конца;
• find(str, start): с помощью параметра start задаётся начальный индекс, и именно с него и выполняется поиск;
• find(str, start, end): посредством параметра end задаётся конечный индекс, поиск выполняется до него.

Python_Pro_970x90-20219-1c8674.png

Когда подстрока не найдена, метод возвращает -1:

    welcome = "Hello world! Goodbye world!"
index = welcome.find("wor")
print(index)       # 6

# ищем с десятого индекса
index = welcome.find("wor",10)
print(index)       # 21

# ищем с 10-го по 15-й индекс
index = welcome.find("wor",10,15)
print(index)       # -1

Замена в строке

Чтобы в Python заменить в строке одну подстроку на другую, применяют метод replace():
• replace(old, new): подстрока old заменяется на new;
• replace(old, new, num): параметр num показывает, сколько вхождений подстроки old требуется заменить на new.

Пример замены в строке в Python:

    phone = "+1-234-567-89-10"

# дефисы меняются на пробелы
edited_phone = phone.replace("-", " ")
print(edited_phone)     # +1 234 567 89 10

# дефисы удаляются
edited_phone = phone.replace("-", "")
print(edited_phone)     # +12345678910

# меняется только первый дефис
edited_phone = phone.replace("-", "", 1)
print(edited_phone)     # +1234-567-89-10

Разделение на подстроки в Python

Для разделения в Python используется метод split(). В зависимости от разделителя он разбивает строку на перечень подстрок. В роли разделителя в данном случае может быть любой символ либо последовательность символов. Этот метод имеет следующие формы:
• split(): в роли разделителя применяется такой символ, как пробел;
• split(delimeter): в роли разделителя применяется delimeter;
• split(delimeter, num): параметром num указывается, какое количество вхождений delimeter применяется для разделения. При этом оставшаяся часть строки добавляется в перечень без разделения на подстроки.

Соединение строк в Python

Рассматривая простейшие операции со строками, мы увидели, как объединяются строки через операцию сложения. Однако есть и другая возможность для соединения строк — метод join():, объединяющий списки строк. В качестве разделителя используется текущая строка, у которой вызывается этот метод:

words = ["Let", "me", "speak", "from", "my", "heart", "in", "English"]

# символ разделителя - пробел
sentence = " ".join(words)
print(sentence)  # Let me speak from my heart in English

# символ разделителя - вертикальная черта
sentence = " | ".join(words)
print(sentence)  # Let | me | speak | from | my | heart | in | English

А если вместо списка в метод join передать простую строку, разделитель будет вставляться уже между символами:

word = "hello"
joined_word = "|".join(word)
print(joined_word)      # h|e|l|l|o

Python_Pro_970x550-20219-0846c7.png

Понравилась статья? Поделить с друзьями:
  • Как в комнате найти подклад
  • Как найти последние изменения в компьютере
  • Как найти airpods если потерял android
  • Как найти образование осадка
  • Как составить план обучения студентов