Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to search for a capital letter within a string and return the list of words with and without capital letters

Tags:

python

string

My homework assignment is to Write a program that reads a string from the user and creates a list of words from the input.Create two lists, one containing the words that contain at least one upper-case letter and one of the words that don't contain any upper-case letters. Use a single for loop to print out the words with upper-case letters in them, followed by the words with no upper-case letters in them, one word per line.

What I know is not correct:

s= input("Enter your string: ")
words = sorted(s.strip().split())
for word in words:
    print (word)

Because it only sorts the sequence if the Capitol is in the first character. For this assignment a character could appear any where within a word. Such as, 'tHis is a sTring'.

I was playing around with a solution that looked similar to this, just to see if I could get the words with CAPS out..But it just wasnt working:

    s = input("Please enter a sentence: ")
while True:
    cap = 0
    s = s.strip().split()
    for c in s:
        if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            print(c[:cap])
            cap += 1
    else:
        print("not the answer")
        break 

But a regular expression would probably do a better job than writing out the whole alphabet.

Any help is much appreciated. Needless to say I am new to python.

like image 660
casper Avatar asked Jul 06 '11 19:07

casper


2 Answers

>>> w = 'AbcDefgHijkL'
>>> r = re.findall('([A-Z])', word)
>>> r
['A', 'D', 'H', 'L']

This can give you all letters in caps in a word...Just sharing the idea

>>> r = re.findall('([A-Z][a-z]+)', w)
>>> r
['Abc', 'Defg', 'Hijk']

Above will give you all words starting with Caps letter. Note: Last one not captured as it does not make a word but even that can be captured

>>> r = re.findall('([A-Z][a-z]*)', w)
>>> r
['Abc', 'Defg', 'Hijk', 'L']

This will return true if capital letter is found in the word:

>>> word = 'abcdD'
>>> bool(re.search('([A-Z])', word))
like image 62
Arindam Roychowdhury Avatar answered Oct 19 '22 23:10

Arindam Roychowdhury


Hint: "Create two lists"

s= input("Enter your string: ")
withcap = []
without = []
for word in s.strip().split():
    # your turn

The way you are using the for .. else in is wrong - the else block is executed when there is no break from the loop. The logic you are trying to do looks like this

for c in s:
    if c.isupper():
        # s contains a capital letter
        # <do something>
        break # one such letter is enough
else: # we did't `break` out of the loop
    # therefore have no capital letter in s
    # <do something>

which you can also write much shorter with any

if any(c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for c in s):
     # <do something>
else:
     # <do something>
like image 27
Jochen Ritzel Avatar answered Oct 19 '22 23:10

Jochen Ritzel