开发者

Why is there a space in sys.argv[]?

argc = len(sys.argv)

if (argc < 3 or argc > 5):
    printusage()
    sys.exit()

insensitive = 1 if ("-i" in sys.argv) else 0
boundaries = 1 if ("-b" in sys.argv) else 0

filename = sys.argv[argc-2]
str = sys.argv[argc-1]

print "Looking for '", str , "' in '" , filename , "'"

The output is

python count_words.py -b -i football.txt goal

Looking for ' goal ' in ' football.txt '

Why is there a space before and after 'goal' and 'football.txt' ? When I try to print the str and filename variable by themselves, they don't开发者_Go百科 have these spaces.

I've also tried using str.strip() in the print, but to no effect.

Any ideas?


The space is not in sys.argv, it is caused by the use of commas when printing. Try

print "Looking for '%s' in '%s'" % (str, filename)

And try to avoid shadowing the builtin str.


It's because you're passing separate strings to the print statement, rather than concatenating them into one string and printing it in one go:

>>> print "a", "b"
a b
>>> print "a" + "b"
ab

Note that concatenating strings is relatively expensive: It's better to use interpolation, like this:

>>> print "A %s with %s" % ("string", "placeholders")
A string with placeholders


It's the commas in your print statement. If you use the following it'll work:

print "Looking for '%s' in '%s'" %(str, filename)


The print statement prints a space between each of its arguments. See the documentation for the print statement:

A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line.

You could try using string concatenation instead:

print "Looking for '" + s + "' in '" + filename + "'"

or better yet, use str.format.

print "Looking for '{0}' in '{1}'".format(s, filename)

Note: avoid using str as a variable name.


Others have already answered your spaces question.

Some other suggestions:

str() is a built-in function so don't assign anything to it or you may wonder later why it doesn't work when you want to use it.

Also:

insensitive = 1 if ("-i" in sys.argv) else 0

is pretty much same as:

insensitive = "-i" in sys.argv


Another suggestion, instead of parsing the argv by yourself, you should try OptionParser that let you handle linux style option/flags.

from optparse import OptionParser
PARSER = OptionParser(usage="""usage: %%prog [-b] file_name""")
PARSER.add_option("-b", "--boundaries", action="store_true", dest="boundaries", help="Boundaries ?")
options, arguments = PARSER.parse_args()
if options.boundaries:
    # -b was activated...
file_name = arguments[0]


Print separates its arguments with a space. Better use str.format.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜