我想拆分列表项,然后为它们添加值。要做到这一点,我需要采取第一句话;将其拆分为一个列表;使用isdigit()
确定列表元素是否为数字,然后将1添加到元素;使用join()
将新列表元素连接在一起。它需要使用带枚举的for循环来完成。
这是我的代码:
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():
答案 0 :(得分:1)
看起来你想要这样的东西
我已将li[0]
和其他变量替换为字符串" Some_Value"因为我不知道那些变量的价值
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
答案 1 :(得分:0)
这是另一种查看解决方案(添加了评论)
的方法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
答案 2 :(得分:0)
' '.join([ str( int(i)+1 ) if i.isdigit() else i for i in a.split() ] )