Как найти все буквы в строке питон

I’m trying to check if a string only contains letters, not digits or symbols.

For example:

>>> only_letters("hello")
True
>>> only_letters("he7lo")
False

Tomerikoo's user avatar

Tomerikoo

18.1k16 gold badges45 silver badges60 bronze badges

asked Sep 6, 2013 at 22:17

user2745401's user avatar

0

Simple:

if string.isalpha():
    print("It's all letters")

str.isalpha() is only true if all characters in the string are letters:

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

Demo:

>>> 'hello'.isalpha()
True
>>> '42hello'.isalpha()
False
>>> 'hel lo'.isalpha()
False

answered Sep 6, 2013 at 22:22

Martijn Pieters's user avatar

Martijn PietersMartijn Pieters

1.0m292 gold badges4018 silver badges3317 bronze badges

7

The str.isalpha() function works. ie.

if my_string.isalpha():
    print('it is letters')

answered Sep 6, 2013 at 22:21

cmd's user avatar

cmdcmd

5,70416 silver badges30 bronze badges

2

For people finding this question via Google who might want to know if a string contains only a subset of all letters, I recommend using regexes:

import re

def only_letters(tested_string):
    match = re.match("^[ABCDEFGHJKLM]*$", tested_string)
    return match is not None

answered Mar 20, 2015 at 13:25

Martin Thoma's user avatar

Martin ThomaMartin Thoma

122k155 gold badges604 silver badges939 bronze badges

1

You can leverage regular expressions.

>>> import re
>>> pattern = re.compile("^[a-zA-Z]+$")
>>> pattern.match("hello")
<_sre.SRE_Match object; span=(0, 5), match='hello'>
>>> pattern.match("hel7lo")
>>>

The match() method will return a Match object if a match is found. Otherwise it will return None.


An easier approach is to use the .isalpha() method

>>> "Hello".isalpha()
True
>>> "Hel7lo".isalpha()
False

isalpha() returns true if there is at least 1 character in the string and if all the characters in the string are alphabets.

answered Jan 7, 2019 at 7:30

Shail's user avatar

ShailShail

8819 gold badges20 silver badges37 bronze badges

Actually, we’re now in globalized world of 21st century and people no longer communicate using ASCII only so when anwering question about “is it letters only” you need to take into account letters from non-ASCII alphabets as well. Python has a pretty cool unicodedata library which among other things allows categorization of Unicode characters:

unicodedata.category('陳')
'Lo'

unicodedata.category('A')
'Lu'

unicodedata.category('1')
'Nd'

unicodedata.category('a')
'Ll'

The categories and their abbreviations are defined in the Unicode standard. From here you can quite easily you can come up with a function like this:

def only_letters(s):
    for c in s:
        cat = unicodedata.category(c)
        if cat not in ('Ll','Lu','Lo'):
            return False
    return True

And then:

only_letters('Bzdrężyło')
True

only_letters('He7lo')
False

As you can see the whitelisted categories can be quite easily controlled by the tuple inside the function. See this article for a more detailed discussion.

answered Jun 12, 2017 at 9:49

kravietz's user avatar

kravietzkravietz

10.5k2 gold badges35 silver badges27 bronze badges

answered Sep 6, 2013 at 22:24

Amilcar Andrade's user avatar

Looks like people are saying to use str.isalpha.

This is the one line function to check if all characters are letters.

def only_letters(string):
    return all(letter.isalpha() for letter in string)

all accepts an iterable of booleans, and returns True iff all of the booleans are True.

More generally, all returns True if the objects in your iterable would be considered True. These would be considered False

  • 0
  • None
  • Empty data structures (ie: len(list) == 0)
  • False. (duh)

answered Dec 18, 2015 at 19:52

hlin117's user avatar

hlin117hlin117

20.4k30 gold badges72 silver badges93 bronze badges

2

(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.

answered Jan 2, 2018 at 6:50

Hemin Patel's user avatar

A pretty simple solution I came up with: (Python 3)

def only_letters(tested_string):
    for letter in tested_string:
        if letter not in "abcdefghijklmnopqrstuvwxyz":
            return False
    return True

You can add a space in the string you are checking against if you want spaces to be allowed.

Anonymous's user avatar

Anonymous

7304 gold badges14 silver badges36 bronze badges

answered Nov 12, 2015 at 14:45

The SuperCuber's user avatar

4

Часто нам нужно найти символ в строке 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() можно использовать в том числе и для поиска общего числа совпадений подстроки.

I am trying to write a python program that checks if a given string is a pangram – contains all letters of the alphabet.

Therefore, "We promptly judged antique ivory buckles for the next prize" should return True while any string that does not contain every letter of the alphabet at least once should return False.

I believe I should be using RegEx for this one, but I’m not sure how. It should look similar to this:

import sys
import re

input_string_array = sys.stdin.readlines()
input_string = input_string_array[0]

if (re.search('string contains every letter of the alphabet',input_string):
    return True
else:
    return False

rypel's user avatar

rypel

4,6562 gold badges24 silver badges36 bronze badges

asked Apr 5, 2016 at 12:54

Maslor's user avatar

2

This is not something I’d solve with a regular expression, no. Create a set of the lowercased string and check if it is a superset of the letters of the alphabet:

import string

alphabet = set(string.ascii_lowercase)

def ispangram(input_string):
    return set(input_string.lower()) >= alphabet

Only if every letter of the alphabet is in the set created from the input text will it be a superset; by using a superset and not equality, you allow for punctuation, digits and whitespace, in addition to the (ASCII) letters.

Demo:

>>> import string
>>> alphabet = set(string.ascii_lowercase)
>>> input_string = 'We promptly judged antique ivory buckles for the next prize'
>>> set(input_string.lower()) >= alphabet
True
>>> set(input_string[:15].lower()) >= alphabet
False

answered Apr 5, 2016 at 12:56

Martijn Pieters's user avatar

Martijn PietersMartijn Pieters

1.0m292 gold badges4018 silver badges3317 bronze badges

3

This is my solution in python:

alphabet = "abcdefghijklmnopqrstuvwxyz"
sentence = input()
sentence = sentence.lower()
missing = ''
for letter in alphabet:
  if letter not in sentence:
    missing = missing+letter
if (len(missing) != 0):
  print("missing", missing)
else:
  print("pangram")

answered Mar 19, 2021 at 17:45

jeonbik's user avatar

You dont need regex. What you want can be done in two lines with good space efficiency.

ms = itertools.chain(range(ord("a"),ord("z")),range(ord("A"),ord("Z")))
flag = all(chr(o) in string for o in ms)

That’s it. string is the string you want to check. flag will be either True or False depending on if all chars are in string or not.

answered Apr 5, 2016 at 13:18

C Panda's user avatar

C PandaC Panda

3,2872 gold badges11 silver badges11 bronze badges

A pangram is a function that contains at least each letter of the alphabet.
I have tried in this way:

def pangram():
n = str(input('give me a word to check if it is a pangram:n'))
n = n.lower()
n = n.replace(' ','')
if not isinstance(n, str):
    return n, False
elif set(n) >= set('abcdefghijklmnopqrstuvxywz'):
    return n, True
else: 
    return n, False

The function isinstance(n, str) checks if n is a string. The function set() gives us a set. For example set(‘penny’) returns {‘y’, ‘e’, ‘p’, ‘n’}… as you see it is a set without the repeated letters.

answered Apr 1, 2017 at 14:33

Emanuela Masucci's user avatar

3

I was doing the same exercise today, maybe it’s not the best aproach, but I think it’s easy to understand.

def ispangram(s):
  stringy = ''
  flag = True
  validLetters = "abcdefghijklmnopqrstuvwxyz"

  #transform the given string in simple string with no symbols only letters
  for char in s.lower():
    if(char in validLetters):
      stringy += char

  #check if all the letters of the alphabet exist on the string
  for char in validLetters:
    if(char in stringy):
      pass
    else:
      flag = False
      break

  return flag

if(ispangram("We promptly judged antique ivory buckles for the next prize")):
  print("It's PANGRAM!")
else:
  print("It's not Pangram :(")

answered Feb 22, 2018 at 18:27

mseromenho's user avatar

2

import string

def ispangram(str1, alphabet=string.ascii_lowercase):
    return ''.join(sorted(set(str1.lower().replace(" ","")))) == alphabet

First changed all alphabets to lowercase and then removed all spaces using replace. Then Converted into set to have unique chars and then used sorted function to sort alphabetically. As sorted function gives a list, so join func to join it without spaces and then compared it to all lowercase chars.

answered Oct 20, 2020 at 11:56

Jay's user avatar

Here is my solution:

def isaPangrams(s):
    alph = list(string.ascii_lowercase)
    s = s.lower()
    s = list(s)

    for letter in alph:
        if letter not in s:
            print('not pangram')
            present='false'
            break
        if letter in s:
            present = 'true'

    if present == 'true':
        print('pangram')

if __name__ == '__main__':
    s = input()
    answer = isaPangrams(s)

Flair's user avatar

Flair

2,5191 gold badge27 silver badges40 bronze badges

answered Jan 7, 2022 at 8:26

CAPTAIN usMAN's user avatar

1

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

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

Добавить комментарий