开发者

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

开发者 https://www.devze.com 2023-03-18 07:09 出处:网络
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-cas

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 letter开发者_开发技巧s. 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.


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


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>


Sounds like regexs would be easier for the first part of the problem (a regex that just looks for [A-Z] should do the trick).

For the second part, I'd recommend using two lists, as that's an easy way to print everything out in one for loop. Have one list of non_upper_words and one of upper_words.

So, the basic outline of the program would be:

  1. split the string into an array of words.
  2. for each word in array: if regex returns true, add to upper_words. Else: add to non_upper_words.
  3. print each word in the first array and then in the second.

I wrote this out in pseudo-code because it's a programming assignment, so you should really write the actual code yourself. Hope it helps!


You can use isupper method for your purpose:

text = 'sssample Text with And without'

uppers = []
lowers = []

# Note that loop below could be modified to skip ,.-\/; and etc if neccessary
for word in text.split():
    uppers.append(word) if word[0].isupper() else lowers.append(word)

EDITED: You can also use islower method the following way:

text = 'sssample Text with And without'

other = []
lowers = []

# Note that loop below could be modified to skip ,.-\/; and etc if neccessary
for word in text.split():
    lowers.append(word) if word.islower() else other.append(word)

OR depends on what you really need you can take a look at istitle method:

titled = []
lowers = []

for word in text.split():
    titled.append(word) if word.istitle() else lower.append(word)

AND with simple if else statement:

titled = []
lowers = []

for word in text.split():       
    if word.istitle():
        titled.append(word) 
    else:
        lower.append(word)


You can use List Comprehensions to get all upper case characters and lower case characters.

def get_all_cap_lowercase_list(inputStr):
    cap_temp_list = [c for c in inputStr if c.isupper()]
    low_temp_list = [c for c in inputStr if c.islower()]
    print("List of Cap {0}  and List of Lower {1}".format(cap_temp_list,low_temp_list))

    upper_case_count = len(cap_temp_list)
    lower_case_count = len(low_temp_list)
    print("Count of Cap {0}  and Count of Lower {1}".format(upper_case_count,lower_case_count))
get_all_cap_lowercase_list("Hi This is demo Python program")

And The output is:

List of Cap ['H', 'T', 'P'] and List of Lower ['i', 'h', 'i', 's', 'i', 's', 'd', 'e', 'm', 'o', 'y', 't', 'h', 'o', 'n', 'p', 'r', 'o', 'g', 'r', 'a', 'm']

Count of Cap 3 and Count of Lower 22


Try doing the following:

  1. Split the string into a list where each item is a separate word.
  2. For every word in that list, iterate through and check for capital letters (consider the string constants such as string.uppercase). If it has a capital letter, insert it onto the front of your result list. If not, append it to the end of your result list.
  3. Iterate through your results, printing them. Or, if you want to avoid iterating, join the items in the string using the newline character \n.


Thank you to everyone for your input and help, it was all very informative. Here is the answer that I finally submitted.

s = input("Please enter a sentence: ")
withcap = []
without = []
for word in s.split():
    if word.islower():
        without.append(word)
    else:
        withcap.append(word)

onelist = withcap + without

for word in onelist:
    print (word)


I think your answer might only be searching for words where the first letter is capitalized. To find words that contain a capital letter anywhere in the word, you'd have to enumerate over each letter in the word, like this:

uin = input("Enter your text: ")

##create lists to hold upper and lower case words
up_words = []
no_up_words = []

for i, word in enumerate(uin.strip().split()):
    if word.islower():
        no_up_words.append(word)
    else: 
        up_words.append(word)

print(up_words, no_up_words)


My regex:

vendor  = "MyNameIsJoe. IWorkInDDFinc."
ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor)

I need split word that would have happened: My Name Is Joe. I Work In DDF inc.

0

精彩评论

暂无评论...
验证码 换一张
取 消