简体   繁体   中英

How to return the result of print statement in a function call in python?

I am a beginner and I am having a problem returning a value in python. The Question is as follows: Write a function called get_capitals. get_capitals should accept one parameter, a string. It should return a string containing only the capital letters from the original string: no lower-case letters, numbers, punctuation marks, or spaces. In short, the function should return the string which will only contain capital letters. My code is:

def get_capitals(a_string):
    for x in a_string:
        ordinal_number=ord(x)
        if ordinal_number>=60 and ordinal_number<=90:
           print(x,end=""))
           # print(ordinal_number)

Using function call

print(get_capitals("CS1301"))

call with the above call the above code i am able to print the result i desire but it returns None. which I am trying to avoid. Can someone tell me how can I return a result of the print function?

As far as my understanding goes, You need a program that only returns letters that is in Capital in a String. I developed a program, have a look.

My Code:

    def get_capitals (a_string):
        upper_case_chars = ""
        for i in a_string:
            if i.isupper():
                upper_case_chars = upper_case_chars + i

        return upper_case_chars


    print (get_capitals("CSFF57456"))

Use list comprehension and join

def get_capitals(a_string):
    return ''.join(c for c in a_string if c.isupper())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM