CodeWars Python Solutions
Find the capitals
Write a function that takes a single string (word
) as argument. The function must return an ordered list containing the indexes of all capital letters in the string.
Example:
Test.assertSimilar( capitals('CodEWaRs'), [0,3,4,6] );
Given Code
Solution 1
def capitals(word): inds = [] i = 0 for l in word: if l.isupper(): inds.append(i) i += 1 return inds
Solution 2
def capitals(word): return [i for (i, c) in enumerate(word) if c.isupper()]
See on CodeWars.com
|
|
Recently Published
Quiz Scoreboard
More to Explore
Quiz From the Vault
Featured Blog Post
You Might Also Like…
Trending Topics
Showdown Scoreboard
More By:
enough
Quiz | Plays | Rating | Category | Featured | Created |
---|---|---|---|---|---|
Country Word Search |
173,590 | 4.29 | Just For Fun | Nov 26, 2009 | |
Blitz: Name A… |
456,608 | 4.61 | Miscellaneous | Sep 24, 2010 | |
The Office: What Character? |
391,673 | 4.27 | Television | Mar 1, 2010 | |
Animated Movie by Characters |
351,349 | 4.56 | Movies | Feb 11, 2010 | |
Game System by Controller |
349,910 | 4.34 | Gaming | Apr 8, 2010 | |
Blitz: Name A… II |
328,993 | 4.50 | Miscellaneous | Oct 12, 2010 |
Go to Creator’s Profile
I’m trying to learn how to use regular expressions but have a question. Let’s say I have the string
line = 'Cow Apple think Woof`
I want to see if line
has at least two words that begin with capital letters (which, of course, it does). In Python, I tried to do the following
import re
test = re.search(r'(b[A-Z]([a-z])*b){2,}',line)
print(bool(test))
but that prints False
. If I instead do
test = re.search(r'(b[A-Z]([a-z])*b)',line)
I find that print(test.group(1))
is Cow
but print(test.group(2))
is w
, the last letter of the first match (there are no other elements in test.group
).
Any suggestions on pinpointing this issue and/or how to approach the problem better in general?
asked Apr 15, 2017 at 4:06
0
The last letter of the match is in group because of inner parentheses. Just drop those and you’ll be fine.
>>> t = re.findall('([A-Z][a-z]+)', line)
>>> t
['Cow', 'Apple', 'Woof']
>>> t = re.findall('([A-Z]([a-z])+)', line)
>>> t
[('Cow', 'w'), ('Apple', 'e'), ('Woof', 'f')]
The count of capitalised words is, of course, len(t)
.
answered Apr 15, 2017 at 4:19
SynedraacusSynedraacus
9451 gold badge8 silver badges19 bronze badges
2
I use the findall
function to find all instances that match the regex. The use len
to see how many matches there are, in this case, it prints out 3
. You can check if the length is greater than 2 and return a True
or False
.
import re
line = 'Cow Apple think Woof'
test = re.findall(r'(b[A-Z]([a-z])*b)',line)
print(len(test) >= 2)
If you want to use only regex, you can search for a capitalized word then some characters in between and another capitalized word.
test = re.search(r'(b[A-Z][a-z]*b)(.*)(b[A-Z][a-z]*b)',line)
print(bool(test))
(b[A-Z][a-z]*b)
— finds a capitalized word(.*)
— matches 0 or more characters(b[A-Z][a-z]*b)
— finds the second capitalized word
This method isn’t as dynamical since it will not work for trying to match 3 capitalized word.
answered Apr 15, 2017 at 4:12
davidhudavidhu
9,2275 gold badges31 silver badges53 bronze badges
1
import re
sent = "His email is abc@some.com, however his wife uses xyz@gmail.com"
x = re.findall('[A-Za-z]+@[A-Za-z.]+', sent)
print(x)
If there is a period at the end of an email ID (abc@some,com.), it will be returned at the end of the email address. However, this can be dealt separately.
answered Jun 10, 2020 at 23:27
Complete the sentences with the correst word
• Capital •twins •late •north •desert •slim •credit •nationality •wavy •driving •middle
e. g Bob has got two credit cards.
1 Has Bill got a … licene
2 My grandparents are in their … fifties
3Magrid is the … city of Spain
4Paul has got two brothers. They are …
5Her father is a … aged man
6Milan is in the … of italy
7 Lisa is tall and … with long, dark hair
8What … is she? She’s French
9In Africa there are a lot of …
10Sally’s hair is short and …
Найдите правильный ответ на вопрос ✅ «Complete the sentences with the correst word • Capital •twins •late •north •desert •slim •credit •nationality •wavy •driving •middle e. g …» по предмету 📘 Английский язык, а если вы сомневаетесь в правильности ответов или ответ отсутствует, то попробуйте воспользоваться умным поиском на сайте и найти ответы на похожие вопросы.
Смотреть другие ответы
Главная » Английский язык » Complete the sentences with the correst word • Capital •twins •late •north •desert •slim •credit •nationality •wavy •driving •middle e. g Bob has got two credit cards. 1 Has Bill got a … licene 2 My grandparents are in their …
Task 4 Complete the sentences with a word
formed from the word in capitals
1. When we raise the temperature, the rate of ___________ increases. (EVAPORATE)
2. I’m interested in doing a _______ on my car to make it more environmentally friendly. (CONVERT)
3. Using a plastic bag once and throwing it away is very _______ (WASTE)
4. Don’t give up – you can achieve anything with ______ and hard work. (PERSEVERE)
Progress
Check – 3
V – 1
I.
Find the word with the same or similar meaning.
Example: dull – c)
a) original b) fascinating c) boring
1. to report
a) to borrow b) to inform c) to explain
2. advertisement
a) commercial b) review c) quiz
3. headline
a) article
b)
title c) conclusion
4. quality
a) popular b) original c) serious
5. handbook
a) manual b) guidebook c) encyclopedia
6. fascinating
a) gripping b) brilliant c) amusing
II.
Complete each sentence with one of the words or phrases below.
whenever wisdom tabloids events celebrate prove
book broadcast issue suggested
1. … contain a lot of photographs
and have a more sensational reporting style.
2. Smoking is bad. Can you … it?
3. Local newspapers give information on different … happening in the
local area.
4. I’d like to … tickets for a group of students to London.
5. Series is a long drama or comedy or documentary that is … in parts,
usually at a certain time of day.
6. The first … of the newspaper “The Daily Courant” was published in London in 1702.
7. … you ask for help, I’ll help you.
8. My uncle … making green tea as it is very good for the health.
9. Mikhail Lomonosov was known as a man of great … .
10. How did you … the turn of the century?
III. The word in capitals above each of the
following sentences can be used to form a word that fits suitably in the blank
space. Fill each blank in this way.
Example: MANAGE
He is the manager of a popular singer.
1. DAY
… newspapers are published on
every day of the week except Sunday.
2. COMMENT
Who is your favourite TV … ?
3. COMMUNCATE
Pamela thinks that the Internet
is the most useful means of … .
4. CULTURE
I prefer to read articles about
… affairs in our town.
5. PRINT
I think CD books will be much
more popular with teenagers of my generation than … books.
IV.
Complete the sentences. Choose the correct variant.
Example: I’ve got a lot of …
(work/ works) to do for the weekend. –
I’ve got a lot
of work
to do for the weekend.
1. What (is/ are) her progress in
English?
2. (Is/ Are) there any news from Andy?
3. Where (is/ are) Granny’s glasses?
4. (Is/ Are) these goods from America?
5. I got a lot of useful (information/ informations).
6. Do you eat much (fruit/ fruits)?
7. I like any kind of (weather/ weathers).
V.
Complete the sentences. Choose the correct variant.
Example: My mother disapproved of … (to read/ reading)
thrillers. —
My mother
disapproved of reading thrillers.
1. I have never dreamed of (to win/ winning) a competition.
2. My sister always enjoys (to go/ going) for a walk.
3. The angry neighbour told the teenagers to stop (to speak/ speaking)
too loud.
4. Do you think she’ll manage (to pass/ passing) her Maths exam?
5. My mum is always at home. She quitted (to work/ working) last year.
6. The teacher reminded us (to bring/ bringing) some flowers to decorate
the classroom.
7. Linda suggested me (to drink/ drinking) a cup of tea now.
поделиться знаниями или
запомнить страничку
- Все категории
-
экономические
43,633 -
гуманитарные
33,652 -
юридические
17,917 -
школьный раздел
611,709 -
разное
16,898
Популярное на сайте:
Как быстро выучить стихотворение наизусть? Запоминание стихов является стандартным заданием во многих школах.
Как научится читать по диагонали? Скорость чтения зависит от скорости восприятия каждого отдельного слова в тексте.
Как быстро и эффективно исправить почерк? Люди часто предполагают, что каллиграфия и почерк являются синонимами, но это не так.
Как научится говорить грамотно и правильно? Общение на хорошем, уверенном и естественном русском языке является достижимой целью.