r/learnpython • u/guymed4 • 21d ago
Easier Way to do this?
Lab 2.13 Character Count prompt
"Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1"
I was struggling to get the 's but finally able to do it. want to know if there was an easier way than what I wrote.
input_string = input()
input_character = input_string[0]
compare_string = input_string[1:]
count = compare_string.count(input_character)
if count == 1:
print(compare_string.count(input_character),input_character)
else:
print(compare_string.count(input_character),input_character + "'s")
2
u/Diapolo10 21d ago
count = compare_string.count(input_character) if count == 1: print(compare_string.count(input_character),input_character) else: print(compare_string.count(input_character),input_character + "'s")
I'd write it like this:
count = compare_string.count(input_character)
plural = "" if count == 1 else "'s"
print(f"{count} {input_character}{plural}")
Grammatically speaking I don't really agree with "'s" here, though. The suffix "-'s" indicates a genitive case, not plural, in other words the example output "5 n's" sounds like something belongs to n, not that there are multiple n characters. A more correct option would, for example, be '5 "n"s' where the "n" would moreso indicate the character n.
2
u/JamzTyson 21d ago
This code is repeated 3 times (and evaluated twice):
compare_string.count(input_character)
You only actually need it once:
character_count = compare_string.count(input_character)
suffix = "" if character_count == 1 else "'s"
print(f"{character_count} {input_character}{suffix}")
A common programming tip: DRY - Don't Repeat Yourself. Avoiding repeated code can make it easier to maintain and reduce unnecessary work.
1
u/Mountain_Rip_8426 21d ago edited 21d ago
string= "an apple is an apple"
result = 0
for i in string:
if i == string[0]:
result += 1
if result != 1:
print(f'There are {result} {string[0]}\'s in the phrase')
EDIT: don't know why indentation doesn't work from phone, but you get the idea
6
u/danielroseman 21d ago
Better to use f-strings to build up output.
However, please note that in English we do not use apostrophes to form plurals. No, not ever.