Stavan Shah
Stavan Shah

Reputation: 33

Splitting list items and adding value to them in python

I want to split list items then add values to them. To do this I am required to take the first sentence; split it into a list; use the isdigit() to determine if the list element is a digit then add 1 to the element; join the new list elements together using join(). It needs to be done using the for loop with enumerate.

This is my code :

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
printer = a.split(" ")
print printer
if printer.isdigit():

Upvotes: 0

Views: 519

Answers (3)

RFV
RFV

Reputation: 839

Here is another way to look at solution (with comments added)

li = ["New York", "London", "Tokyo"] #This is an example list for 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
printer = a.split(" ")
print printer

new_printer = []
for word in printer:
    if word.isdigit():
        word = str(int(word) + 1) #this increments word by 1. first we have to convert the string value of word to number (int) and then add one (+ 1), and then convert it back to a string (str) and save it back to word
    new_printer.append(word) # this adds word (changed or not) at the end of new_printer
end_result = " ".join(new_printer) #this joins all the words in new_printer and places a space between them

print end_result

Upvotes: 0

Transhuman
Transhuman

Reputation: 3547

' '.join([ str( int(i)+1 ) if i.isdigit() else i for i in a.split() ] )

Upvotes: 0

saurabh baid
saurabh baid

Reputation: 1877

Looks like you want something like this
I have replaced li[0] and other variables with a string "Some_Value" because I did not knew the value of those variables

a="You would like to visit " + "Some_Value" +" as city 1 and " + "Some_Value" + " as city 2 and "+ "Some_Value" + " as city 3 on your trip"
a = a.split(" ")
index = 0

for word in a:
    if word.isdigit():
        a[index] = str(int(word) + 1)
    index += 1
print " ".join(a)

OP
You would like to visit Some_Value as city 2 and Some_Value as city 3 and Some_Value as city 4 on your trip

Upvotes: 1

Related Questions