Search code examples
pythonpython-3.xstringuser-input

Is it possible to add to a string based on user input python


I am currently working on a program that takes in user inputs, and depending on that users input the string should change. I was wondering if there was a way I could alter the string once the user input has been received. The following is a sample code.

title = input('Title: ')
subtitle = input('Subtitle: ')
chapter = input('Chapter: ')
subchapter = input('Subchapter: ')

title1 = '/title{}'.format(title)
subtitle1 = '/subtitle{}'.format(subtitle)
chapter1 = '/chapter{}'.format(chapter)
subchapter1 = '/subchapter{}'.format(subchapter)

output_txt = title1+subtitle1+chapter1+subchapter1
print(output_txt)
  1. Input taken by user: Should be a number
  2. The input would then be formatted to its perspective string
  3. Based on the user input the string, output_txt, should be formatted accordingly

Scenario 1: User Input

Title: 4
Subtitle:
Chapter: 12
Subchapter: 1

output_txt should be

output_txt = '/title4/chapter12/subchapter1'

Scenario 2: User Input

Title: 9
Subtitle: 
Chapter: 2
Subchapter: 

output_txt should be

output_txt = '/title9/chapter2'

I have been using if elif but since there could be multiple combinations I do not think doing it that way is the most efficient.

Any help or tips in the right direction is greatly appreciated


Solution

  • Here's an approach that uses a regular expression for input validation and list comprehensions to gather the inputs and build the output string.

    import re
    
    
    def get_input( label: str = None ) -> int:
        entry = input(label + ': ')
    
        if re.match(r'^\d+$', entry) is None:
            return None
    
        if int(entry) <= 0:
            return None
    
        return int(entry)
    
    
    tpl_labels = ('Title', 'Subtitle', 'Chapter', 'Subchapter')
    
    lst_values = [get_input(x) for x in tpl_labels]
    
    output_txt = '/'.join([f'{x.lower()}{y}' for x, y in zip(tpl_labels, lst_values) if y])
    
    if not output_txt:
        print('No valid responses given.')
    else:
        output_txt = '/' + output_txt
        print(output_txt)
    

    The get_input() function expects each value entered by the user to be a positive integer. All other input is silently ignored (and None is returned).