是否可以根据用户输入Python添加到字符串中

发布于 2025-01-29 10:20:39 字数 1066 浏览 4 评论 0原文

我目前正在处理一个吸收用户输入的程序,并且根据用户输入字符串应更改。我想知道,一旦收到用户输入,我是否有一种方法可以更改字符串。以下是示例代码。

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. 用户获取的输入:应该是一个数字
  2. ,然后将输入格式化为
  3. 基于用户输入字符串

的透视字符串。方案1: 用户输入

Title: 4
Subtitle:
Chapter: 12
Subchapter: 1

output_txt应该是

output_txt = '/title4/chapter12/subchapter1'

方案2: 用户输入

Title: 9
Subtitle: 
Chapter: 2
Subchapter: 

output_txt应该是

output_txt = '/title9/chapter2'

我一直在使用elif,但是由于可能有多种组合,所以我认为这样做不是最有效的。

朝着正确方向的任何帮助或技巧都非常感谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

和影子一齐双人舞 2025-02-05 10:20:39

在为变量分配字符串值时,您可以使用IF-ELSE条件

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

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

output_txt = title1+subtitle1+chapter1+subchapter1
print(output_txt)

You could use an if-else condition while assigning string values to the variable

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

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

output_txt = title1+subtitle1+chapter1+subchapter1
print(output_txt)
べ繥欢鉨o。 2025-02-05 10:20:39

让我向您介绍 typer

typer将帮助您用Python轻松地创建一个CLI,

以便您的代码 轻松创建CLI接近这样的接近

import typer

# By defining the data type, we can set the input only a number
def main(title: int = None, subtitle: int = None, chapter: int = None, subchapter: int = None):
    title = f'/title{title}' if title else ''
    subtitle = f'/subtitle{subtitle}' if subtitle else ''
    chapter = f'/chapter{chapter}' if chapter else ''
    subchapter = f'/subchapter{subchapter}' if subchapter else ''

    output_txt = title+subtitle+chapter+subchapter
    print(output_txt)


if __name__ == "__main__":
    typer.run(main)

,您只需要通过为每个所需的参数添加参数来运行它

python script_name.py --title 5 --chapter 2 --subchapter 7

Let me introduce you to typer

typer will help you to create a CLI with python easily

for your code can be approached like this

import typer

# By defining the data type, we can set the input only a number
def main(title: int = None, subtitle: int = None, chapter: int = None, subchapter: int = None):
    title = f'/title{title}' if title else ''
    subtitle = f'/subtitle{subtitle}' if subtitle else ''
    chapter = f'/chapter{chapter}' if chapter else ''
    subchapter = f'/subchapter{subchapter}' if subchapter else ''

    output_txt = title+subtitle+chapter+subchapter
    print(output_txt)


if __name__ == "__main__":
    typer.run(main)

And you just need to run it by adding the parameter for each one you need

python script_name.py --title 5 --chapter 2 --subchapter 7
北方。的韩爷 2025-02-05 10:20:39

这是一种使用正则表达式进行输入验证的方法,并列出综合以收集输入并构建输出字符串。

import re


def get_input( label: str = None ) -> int:
    entry = input(label + ': ')

    if re.match(r'^\d+

get_input()函数期望用户输入的每个值是一个正整数。所有其他输入都被默默地忽略(无将返回)。

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

get_input()函数期望用户输入的每个值是一个正整数。所有其他输入都被默默地忽略(无将返回)。

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+

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

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

如梦 2025-02-05 10:20:39

只是为了完整性,您可能还需要测试一个数字。

# Test

def test_for_int(testcase):
    try:
        int(testcase)
        return True
    except ValueError: # Strings
        return False
    except TypeError: # None
        return False

# Get the inputs

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

# Run the tests and build the string

output_txt = ''
if test_for_int(title):
    output_txt += '/title{}'.format(title)
if test_for_int(subtitle):
    output_txt += '/subtitle{}'.format(subtitle)
if test_for_int(chapter):
    output_txt += '/chapter{}'.format(chapter)
if test_for_int(subchapter):
    output_txt += '/subchapter{}'.format(subchapter)
    
print(output_txt)

Just for completeness you might want to test for a number as well.

# Test

def test_for_int(testcase):
    try:
        int(testcase)
        return True
    except ValueError: # Strings
        return False
    except TypeError: # None
        return False

# Get the inputs

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

# Run the tests and build the string

output_txt = ''
if test_for_int(title):
    output_txt += '/title{}'.format(title)
if test_for_int(subtitle):
    output_txt += '/subtitle{}'.format(subtitle)
if test_for_int(chapter):
    output_txt += '/chapter{}'.format(chapter)
if test_for_int(subchapter):
    output_txt += '/subchapter{}'.format(subchapter)
    
print(output_txt)
有木有妳兜一样 2025-02-05 10:20:39

您可以做这样的事情...

def get_user_input(message):
    user_input = input(message+' : ')
    if user_input == '' or user_input.isdigit() == True:
        return user_input
    else:
        return False


def f():
    title   = ''
    while True:
        title = get_user_input('title')
        if title == False:
            continue
        else:
            break



    subtitle   = ''
    while True:
        subtitle = get_user_input('subtitle')
        if subtitle == False:
            continue
        else:
            break


    chapter   = ''
    while True:
        chapter = get_user_input('chapter')
        if chapter == False:
            continue
        else:
            break

    subchapter   = ''
    while True:
        subchapter = get_user_input('subchapter')
        if subchapter == False:
            continue
        else:
            break

    s  = ''
    s += '/title'+str(title) if title != '' else ''
    s += '/subtitle'+str(subtitle) if subtitle != '' else ''
    s += '/chapter'+str(chapter) if chapter != '' else ''
    s += '/subchapter'+str(subchapter) if subchapter != '' else ''

    return s

输出...

title : 1
subtitle : 2
chapter : 3
subchapter : 4

'/title1/subtitle2/chapter3/subchapter4'

title : 1
subtitle : 
chapter : 3
subchapter : 

'/title1/chapter3'

显然,您需要为您的特定目的为代码添加一些更改。

You can do something like this...

def get_user_input(message):
    user_input = input(message+' : ')
    if user_input == '' or user_input.isdigit() == True:
        return user_input
    else:
        return False


def f():
    title   = ''
    while True:
        title = get_user_input('title')
        if title == False:
            continue
        else:
            break



    subtitle   = ''
    while True:
        subtitle = get_user_input('subtitle')
        if subtitle == False:
            continue
        else:
            break


    chapter   = ''
    while True:
        chapter = get_user_input('chapter')
        if chapter == False:
            continue
        else:
            break

    subchapter   = ''
    while True:
        subchapter = get_user_input('subchapter')
        if subchapter == False:
            continue
        else:
            break

    s  = ''
    s += '/title'+str(title) if title != '' else ''
    s += '/subtitle'+str(subtitle) if subtitle != '' else ''
    s += '/chapter'+str(chapter) if chapter != '' else ''
    s += '/subchapter'+str(subchapter) if subchapter != '' else ''

    return s

Output...

title : 1
subtitle : 2
chapter : 3
subchapter : 4

'/title1/subtitle2/chapter3/subchapter4'

title : 1
subtitle : 
chapter : 3
subchapter : 

'/title1/chapter3'

Obviously you need to add few changes to the code for your specific purpose.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文