Python: efficient syntax for creating a list composed of strings
I am new to python and essentially trying to figure out the syntax that replicates this functionality: 开发者_高级运维strings = ["foo", "bar", "apple"]
with something similar to strings = [foo, bar, apple]
so that I don't have to put quotes around all the entries. Thanks!
strings = "foo bar apple".split()
strings = r"foo, bar, apple".split(", ")
You could place all the strings in a text file, one string on each line. Then strings = list(open("datafile", "r"))
.
I would say that there is no easier way to create a list of strings than what you're already doing.
As other answers have pointed out, there are ways to put all the strings in one big string or file, then split them, but in my opinion that is more difficult to type than the quotes, particularly if you have a decent IDE that automatically closes string quotes. Also, the syntax you're already using is what anyone else who reads your code will expect; using something else just adds unnecessary confusion for almost zero gain.
There is two major differences between what you posted:
The quotes "" and '' indicate that it is a string, just like [1,2,3] would be a list of integers. If you remove the quotes, you are essentially creating a list of python objects. A python object is basically the foundation of all python classes, e.g. integers and strings are python objects are their most basic level.
You can do something like:
foo = "foo"
bar = "bar"
apple = "apple"
strings = [foo,bar,apple]
If you have a lot of elements to write, you can use a program to do that (such an incredible idea from a developper ! ), and then you copy-paste the result:
li = []
ch = ("You have entered an empty string ''\n"
'Type ENTER alone if you want to stop.\n'
'Type anything if you want to record the empty string : ')
while True:
e = raw_input('enter : ')
if e=='':
x = raw_input(ch)
if x=='': break
li.append(e)
print
print li
Example:
enter : 123
enter : ocean
enter : flower
enter :
You have entered an empty string ''
Type ENTER alone if you want to stop.
Type anything if you want to record the empty string : k
enter : once upon a time
enter : 14 * 4
enter :
You have entered an empty string ''
Type ENTER alone if you want to stop.
Type anything if you want to record the empty string :
['123', 'ocean', 'flower', '', 'once upon a time', '14 * 4']
What you have not to type but only copy is:
['123', 'ocean', 'flower', '', 'once upon a time', '14 * 4']
精彩评论