0

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)
1
  • 1
    Can you fix your indentation? Commented Oct 12, 2016 at 10:26

3 Answers 3

2

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'
Sign up to request clarification or add additional context in comments.

4 Comments

But what does '{0} as city {1}' in your code mean??
If the arguments in format are in the same order as the references {} in the string, the numbers are optional.
@StavanShah it is string formatting you can read about it here: docs.python.org/2/library/stdtypes.html#str.format
@nostradamus numbers are optional, but if you explicitly specify them, you format function will work slightly faster
0

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')

Comments

0

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

1 Comment

sorry, it should be like this: a = "You would like to visit %s on your trip" % (cities_str)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.