Python实现:提取并拼接两输入字符串中的大写字母
Python Solution to Extract and Concatenate Uppercase Letters from Two Strings
Got it, let's work through this problem with a straightforward, easy-to-follow solution. The goal is to grab all uppercase letters from two input strings (keeping their original order), stick them together, and then show both the original inputs and the final result.
Breakdown of the Approach:
- Grab User Input: First, we'll ask the user to enter the two strings we need to process.
- Filter Uppercase Letters: We'll use a helper function to loop through each character in a string, check if it's uppercase (using
str.isupper()), and collect those characters in a list—this ensures we keep their original occurrence order. - Combine Results: Extract uppercase letters from both strings and concatenate the two resulting strings into one final output.
- Display Everything: Finally, we'll print out the original strings and the combined uppercase result so the user can see the transformation clearly.
Full Code Implementation:
# Get the two input strings from the user string1 = input("Enter the first string: ") string2 = input("Enter the second string: ") def extract_uppercase(input_str): # Initialize an empty list to store uppercase characters uppercase_chars = [] # Iterate through each character in the input string for char in input_str: # Check if the current character is uppercase if char.isupper(): uppercase_chars.append(char) # Convert the list of characters to a single string and return it return ''.join(uppercase_chars) # Extract uppercase from both strings and concatenate the results final_result = extract_uppercase(string1) + extract_uppercase(string2) # Print out the original strings and the final result print("\nOriginal Inputs:") print(f"String 1: {string1}") print(f"String 2: {string2}") print(f"\nFinal Result (Concatenated Uppercase Letters): {final_result}")
Example Test Run:
If you input:
Enter the first string: HeLLo WoRLd! Enter the second string: I LoVe PyThOn
The output will look like this:
Original Inputs: String 1: HeLLo WoRLd! String 2: I LoVe PyThOn Final Result (Concatenated Uppercase Letters): HLLWRLDILVPTH
This solution is efficient, readable, and strictly preserves the order of uppercase letters as they appear in the original strings.
内容的提问来源于stack exchange,提问作者Psb Sai Krishna
相关产品推荐
相关产品推荐

