Reputation: 33
This Code Works Fine.....But it's like static. I don't know what to do to make it work in dynamic way? I want:- When user inputs 3 number of cities it should give
a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city 2 and "+li[2]+" as city 3 on your trip"
Similaraly when input is 5 cities it should go to 5 times
li = []
global a
number_of_cities = int(raw_input("Enter Number of Cities -->"))
for city in range(number_of_cities):
li.append(raw_input("Enter City Name -->"))
print li
a="You would like to visit "+li[0]+" as city 1 and " +li[1]+ " as city 2 and "+li[2]+" as city 3 on your trip"
print a
a = a.split(" ")
print "\nSplitted First Sentence looks like"
print a
print "\nJoined First Sentence and added 1"
index = 0
for word in a:
if word.isdigit():
a[index] = str(int(word)+1)
index += 1
print " ".join(a)
Upvotes: 0
Views: 872
Reputation: 117
create another for loop and save your cities to an array. afterwords, concat the array using "join" and put put everything inside the string:
cities = []
for i in range(0,len(li), 1):
cities.append("%s as city %i" % (li[i], i))
cities_str = " and ".join(cities)
a = "You would like to visit %s on your trip" % (cities_str) # edited out the + sign
Upvotes: 0
Reputation: 52949
You can build the string with a combination of string formatting, str.join
and enumerate
:
a = "You would like to visit {} on your trip".format(
" and ".join("{} as city {}".format(city, i)
for i, city in enumerate(li, 1)))
str.join()
is given a generator expression as the iterable argument. The curly braces ({}
) in the strings are replacement fields (placeholders), which will be replaced by positional arguments when formatting. For example
'{} {}'.format('a', 'b')
will produce the string "a b"
, as will
# explicit positional argument specifiers
'{0} {1}'.format('a', 'b')
Upvotes: 0
Reputation: 1151
You should do something like this
a = 'You would like to visit ' + ' and '.join('{0} as city {1}'.format(city, index) for index, city in enumerate(li, 1)) + ' on your trip'
Upvotes: 2