I’m writing out a small snippet that grabs all letters that start with a capital letter in python . Here’s my code
def WordSplitter(n):
list1=[]
words=n.split()
print words
#print all([word[0].isupper() for word in words])
if ([word[0].isupper() for word in words]):
list1.append(word)
print list1
WordSplitter("Hello How Are You")
Now when I run the above code. Im expecting that list will contain all the elements, from the string , since all of the words in it start with a capital letter.
But here’s my output:
@ubuntu:~/py-scripts$ python wordsplit.py
['Hello', 'How', 'Are', 'You']
['You']# Im expecting this list to contain all words that start with a capital letter
Chris Seymour
82.6k30 gold badges158 silver badges197 bronze badges
asked Nov 3, 2012 at 2:14
0
You’re only evaluating it once, so you get a list of True and it only appends the last item.
print [word for word in words if word[0].isupper() ]
or
for word in words:
if word[0].isupper():
list1.append(word)
answered Nov 3, 2012 at 2:17
Joran BeasleyJoran Beasley
109k12 gold badges157 silver badges177 bronze badges
You can take advantage of the filter
function:
l = ['How', 'are', 'You']
print filter(str.istitle, l)
pydsigner
2,7101 gold badge22 silver badges33 bronze badges
answered Nov 3, 2012 at 2:35
1
I have written the following python snippet to store the capital letter starting words into a dictionary as key and no of its appearances as a value in this dictionary against the key.
#!/usr/bin/env python
import sys
import re
hash = {} # initialize an empty dictinonary
for line in sys.stdin.readlines():
for word in line.strip().split(): # removing newline char at the end of the line
x = re.search(r"[A-Z]S+", word)
if x:
#if word[0].isupper():
if word in hash:
hash[word] += 1
else:
hash[word] = 1
for word, cnt in hash.iteritems(): # iterating over the dictionary items
sys.stdout.write("%d %sn" % (cnt, word))
In the above code, I shown both ways, the array index to check for the uppercase start letter and by using the regular expression. Anymore improvement suggestion for the above code for performance or for simplicity is welcome
answered Dec 12, 2013 at 6:37
Ibrahim QuraishIbrahim Quraish
3,8392 gold badges28 silver badges35 bronze badges
In this post, we will learn how to extract uppercase words in string Python with examples. We have used Regular expression to extract capital words from a given string.” A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression”.We will cover extracting uppercase words from lists in Python, extracting alphanumeric uppercase words from strings in Python, Extract Only uppercase letters from strings in Python, Count uppercase letters from strings in Python
In this example, we have extracted all uppercase words from Python string using Regular expression. In such a case first, we have to import the Regular expression module in our program using “import re”.The regular expression is as follows. The re module findall() function will return the word that matches the given pattern.
- [A-Z]: It extracts capital letters between A-Z.
- b: Start of word
import re strText = 'Welcome to DEVENUM.COM,LET FIND UPPER CASE STRING'; print(re.findall(r'b[A-Z]+(?:s+[A-Z]+)*b', strText))
Output
['DEVENUM', 'COM', 'LET FIND UPPER CASE STRING']
2. How to extract uppercase words in string Python using Regex
In this example, We are using the Regular expression ‘[A-Z]+’ to extract the uppercase letter and upper words from a string. Let us understand code and output.
import re myStr = "Welcome folks'S TO DEVENUM! HOW ARE YOU" pattern = '[A-Z]+' print(re.findall(pattern, myStr))
Output
[' TO DEVENUM', ' HOW ARE YOU']
3. Extract uppercase words from list in Python
To extract uppercase words from a list in Python. We have iterated over the list using for loop and on each iteration, we have extracted uppercase words using the Regular expression using the re.findall() function and display the result.
import re mylist = ['Welcome','to','DEVENUM','COM','LET', 'FIND','CASE'] for item in mylist: print(re.findall(r'b[A-Z]+(?:s+[A-Z]+)*b', item))
Output
[] [] ['DEVENUM'] ['COM'] ['LET'] ['FIND'] ['CASE']
4. Extract uppercase alphanumeric words of string in Python
We have used alphanumeric words from a string.We have used Regular expression [A-Z0-9][A-Z0-9]+|b[A-Z] where 0-9 used to include digit while matching the string.
import re myStr = "Welcome D2'S TO D56EV ENUM! H69OW A89E Y20OU" pattern = '[A-Z0-9][A-Z0-9]+|b[A-Z]*b' print(re.findall(pattern, myStr))
Output
['D2', 'TO', 'D56EV', 'ENUM', 'H69OW', 'A89E', 'Y20OU']
5. Extract Only uppercase letters from string Python
To find all the upper case letters from a string. We have used the filter function along with lambda and checked if the character in a string is uppercase using isupper() method. To return a list we have converted the result to a list using the list() method.
strText = 'Welcome to DEVENUM.COM'; def Is_upper_Letter(myStr): return list(filter(lambda char: char.isupper(), myStr)) print(Is_upper_Letter(strText))
Output
['W', 'D', 'E', 'V', 'E', 'N', 'U', 'M', 'C', 'O', 'M']
6. Count uppercase letters in string Python
To find the count of uppercase letters in a given string. We have iterated over each character of the string by using generator expression. When the upper case character is found, return the character to the sum function and when iteration is over, the sum function will return the count of all upper case letters in the string.
strText = 'Welcome to DEVENUM.COM'; UpperCase_count = sum(1 for item in strText if item.isupper()) print('Upper case letter in String :',UpperCase_count)
Output
Upper case letter in String :11
Summary
In this post, we have learned How to extract uppercase words in string Python by using regular expressions and findall() function of the re module. We have also covered, extracting uppercase words from lists in Python, extracting alphanumeric uppercase words from strings in Python, Extract Only uppercase letters from strings in Python, Count uppercase letters from strings in Python
Someone in one of my online editing groups wanted to find all the acronyms and initialisms in their document—any word comprising two or more capital (‘cap’) letters (e.g. AB, CDEF, GHIJK, etc.). They wanted a command that would find each one so they could check it (possibly against a glossary), then click Find Next to jump to the next one.
Wildcards to the rescue!
Here’s how:
- Press Ctrl+H to open the Find and Replace window.
- Click the Find tab (we only want to find these, not replace them with anything else).
- Click More to show further options.
- Select the Use wildcards checkbox.
- In the Find what field, type: <[A-Z]{2,}>
- Click Find next to find the first string of two or more caps.
- Keep clicking Find next to jump to the next string of two or more caps.
How this works:
- The opening and closing arrow brackets (< and >) specify that you want a single whole word, not parts of a word. Without these, you would find each set of caps (e.g. in the string ABCDEF, you would find ABCDEF, then BCDEF, then CDEF, then DEF, then EF, before moving on to the next set of caps).
- [A-Z] specifies that you want a range (the [ ] part) of caps that fall somewhere in the alphabet (A-Z). If you only wanted capped words that started with, say, H through to M, then you’d change the range to [H-M] and all other capped words starting with other letters would be ignored.
- {2,} means you want to find capped words with at least two letters in the specified range (i.e. A-Z). If you only wanted to find two- and three-letter capped words, then you’d change this to {2,3}, and all capped word of four or more letters would be ignored. By not specifying a number after the comma, the ‘find’ will find capped words of any length containing at least two letters.
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS
Contact US
Thanks. We have received your request and will respond promptly.
Log In
Come Join Us!
Are you a
Computer / IT professional?
Join Tek-Tips Forums!
- Talk With Other Members
- Be Notified Of Responses
To Your Posts - Keyword Search
- One-Click Access To Your
Favorite Forums - Automated Signatures
On Your Posts - Best Of All, It’s Free!
*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.
Posting Guidelines
Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Students Click Here
Finding capital letters in WordFinding capital letters in Word(OP) 12 Sep 07 14:13 Hi, Red Flag SubmittedThank you for helping keep Tek-Tips Forums free from inappropriate posts. |
Join Tek-Tips® Today!
Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.
Here’s Why Members Love Tek-Tips Forums:
- Talk To Other Members
- Notification Of Responses To Questions
- Favorite Forums One Click Access
- Keyword Search Of All Posts, And More…
Register now while it’s still free!
Already a member? Close this window and log in.
Join Us Close
10000+ результатов для ‘find capital letters’
Capital letters
Групповая сортировка
от Bestteachers
Capital letters
Сопоставить
от Dariat123
capital letters
Сопоставить
от Balqeesa27
Capital and small letters
Диаграмма с метками
от Inlandia
Numbers 0-10 (Capital letters)
Угадай буквы
от Nataliakrasilnikova
numbers
Alphabet (capital letters)
Анаграмма
от Nataliakrasilnikova
5-7
English
alphabet
Capital letters
Сопоставить
от Abcstudio090
Capital and small letters
Сопоставить
от Polunochnik
capital letters
Классификация
от Onetwospeak
Letters Capital Low case
Сопоставить
от Mashaskor
phonics
Capital letters
Групповая сортировка
от Onetwospeak
Capital letters
Найди пару
от Vinnyone1527
Capital letters
Викторина
от Alexkrutikova
capital letters
Сопоставить
от Novorossiysk
Capital letters
Сбить воздушный шар
от Petelena987
CVC reading Capital letters
Откройте поле
от Lena45
cooking, but with letters
Случайные карты
от Saturntiger
letters
capital letters + small letters
Сопоставить
от Mayasavkina
letters capital and small
Сопоставить
от Bvaleriya18
actbigmopdenfrhch
Случайные карты
от Inessadelmar
letters
gg1 capital letters
Правда или ложь
от Info193
Capital letters AS1
Пропущенное слово
от Sonyasamsonova
ew2 unit2 capital letters
Найди пару
от Olgashatalova
Capital and small letters abcd
Самолет
от Speakyboom
Letters «A,C,T, B,I,G»
Случайные карты
от Inessadelmar
letters
Quiz Capital and small letters
Викторина
от Hinatochka95
Letters capital lowercase
Совпадающие пары
от Chuvasheva
Дошкольник
1-й класс
Copy of capital letters
Сопоставить
от Novorossiysk
Letters Capital Low case
Сопоставить
от Berdmary96
Bob Bug. Capital letters
Сопоставить
от Wishtree2012
Small and capital letters
Совпадающие пары
от Olesija19821711
Small and capital letters
Самолет
от Ek70572
Miss! Miss! capital letters
Сопоставить
от Wishtree2012
Alphabet capital letters
Случайное колесо
от Alinkateacher
Match capital and low case letters
Сопоставить
от Dgafshin
Fly High 1
Letters with sounds A-Q
Сопоставить
от Olgushka079
Sounds letters
Spotlight 2
Find a capital
Диаграмма с метками
от Loading
capital/small letters A-F
Найди пару
от 610609q
find Capital ABCD
Погоня в лабиринте
от Speakyboom
AS1 Capital and small letters A-M
Найди пару
от Yuf994110
7-9
English
Academy Stars 1
Spotlight 2. The capital and small letters 3
Сопоставить
от Veradivniy
Spotlight 2
Numbers 1-10 (capital letters)
Анаграмма
от Evger8888
Letters (match capital and small)
Сопоставить
от Mmgukasova
Fish and Chips capital letters
Сопоставить
от Wishtree2012
Letters Capital Low case review
Сопоставить
от Bilingvaspb
Spotlight 2. The capital and small letters 2
Сопоставить
от Veradivniy
Spotlight 2
Find letters A-C
Самолет
от Bestteachers
The Odd pet capital letters
Сопоставить
от Wishtree2012
Letters and sounds
Диаграмма с метками
от Olgushka079
Primary
Sounds letters
Spotlight 1
Mum Bug’s bag. Capital letters
Сопоставить
от Wishtree2012
Zak the Vet. Capital letters
Сопоставить
от Wishtree2012
FF2 Unit 1 capital letters
Сопоставить
от Isedept4
AS 1 Unit 1 Capital and small letters N-Z
Найди пару
от Yuf994110
7-9
English
Academy Stars 1
Find pairs (letters A-D)
Совпадающие пары
от Olgayurievnaa
Family and friends starter
Capital and small letters confusing words
Найди пару
от Saturntiger
Spotlight 2. The capital and small letters 1
Сопоставить
от Veradivniy
Spotlight 2
Alphabet matching Capital letter and lower case letters
Сопоставить
от Yulias19
Spotlight 1
Spotlight 2
A-H letters- sounds- words
Групповая сортировка
от Olgushka079
Primary
Sounds letters
Spotlight 1
Copy of Capital and small letters
Сопоставить
от Nastik010493
letters capital and small (till o)
Сопоставить
от Olga121