简体   繁体   中英

Concatenate User Input With Predefined Array

I'm trying to create a tool to ask for user input (text), then add predefined text (an array of 10 words) to the beginning of that input then pass the concatenated 10 values through a command.

This is where I was going with it but I don't know where to go from here:
variable1 = input('Enter XX') variable2 = array('dog', 'cat', 'dog2', 'cat2', 'dog3', 'cat3', 'dog4', 'cat4', 'dog5', 'cat5')

Once I have all ten of the values (maybe a third variable, an array?) I was going to use a for loop to run each of them through a command. How do I go about creating a variable (or something else) that contains all 10 of concatenated values?

You can use the str.join function to concatenate your values.

variable3 = " ".join(variable2) + " " + variable1

I think the use of input is really risky... you probably should use raw_input instead.

In [17]: var2
Out[17]: ['dog', 'cat', 'dog2', 'cat2', 'dog3', 'cat3', 'dog4', 'cat4', 'dog5', 'cat5']

In [18]: var1=input('Enter XX')
Enter XX100

In [19]: [i+str(var1) for i in var2]
Out[19]: 
['dog100',
 'cat100',
 'dog2100',
 'cat2100',
 'dog3100',
 'cat3100',
 'dog4100',
 'cat4100',
 'dog5100',
 'cat5100']

In [20]: ls=[str(var1)+i for i in var2]
Out[20]: 
['100dog',
 '100cat',
 '100dog2',
 '100cat2',
 '100dog3',
 '100cat3',
 '100dog4',
 '100cat4',
 '100dog5',
 '100cat5']

In [24]: " ".join(ls)
Out[24]: '100dog 100cat 100dog2 100cat2 100dog3 100cat3 100dog4 100cat4 100dog5 100cat5'
 variable1 = input('Enter XX')
 lst = ['dog', 'cat', 'dog2', 'cat2', 'dog3', 'cat3', 'dog4', 'cat4', 'dog5', 'cat5']
 concated = ''.join(lst) + variable1

If user input 'abc' concated will be equal to 'abcdogcatdog2cat2dog3cat3dog4cat4dog5cat5'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM