打印组合成连续字符串的输入字符串

时间:2020-02-05 04:28:09

标签: python arguments

有人可以帮我为cli写一个参数,以便将“输入字符串”打印为组合的连续字符串吗? 如何使它成为执行我想要的工作的真实代码?

parser.add_argument('-c','--combine', action='store', dest='store_combined', help='Print input strings combined in a continuous string')

args = parser.parse_args()

因此,如果我运行$ python HW3_cli.py -c这些字符串被连接起来,那么我将得到TheseStringsGetConcatenated作为印刷品。

我还可以打印每个字符串的长度吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试将字符串用引号引起来:

python HW3_cli.py -c "These Strings Get Concatenated" 

然后,您可以在代码中按如下所示按空格分割

args = parser.parse_args() 
print(args.store_combined.split())
#['These', 'Strings', 'Get', 'Concatenated']

答案 1 :(得分:0)

始终理想的是在quotes(“”)下传递字符串,否则将很难区分什么是参数和什么是值

import argparse
import sys

parser = argparse.ArgumentParser(prog='HW3_cli.py')
parser.add_argument('-c','--combine', action='store', dest='store_combined', help='Print input strings combined in a continuous string')
options = parser.parse_args(sys.argv)

print ''.join(options.store_combined.split())
print len(''.join(options.store_combined.split()))

python HW3_cli.py -c "These Strings Get Concatenated"

TheseStringsGetConcatenated
27

如评论部分所述:如果您希望输出单个字符串的长度,请执行以下操作

import argparse
import sys

parser = argparse.ArgumentParser(prog='HW3_cli.py')
parser.add_argument('-c','--combine', action='store', dest='store_combined', help='Print input strings combined in a continuous string')
options = parser.parse_args(sys.argv)

print ''.join(options.store_combined.split())
for i in options.store_combined.split():
    print len(i),

python HW3_cli.py -c "These Strings Get Concatenated"

TheseStringsGetConcatenated
5 7 3 12

让我知道您是否需要

相关问题