如何在Python中以有序的方式添加逗号?

时间:2016-04-26 09:33:17

标签: python

我正在制作一个“wordfinder”类型的脚本,你可以在其中键入一个单词并返回找到该单词的位置。但是,如果单词出现的次数更多,我不希望它说出来

这个词出现在以下位置:3和4和5 ......

我想说:

这个词出现在位置:3,4和5 ......

此时,如果有两个位置出现,则返回:

这个词出现在位置:3和4以及......

到目前为止,这是我的代码:

 sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"

List=[]

for i in sentence.split(" "):
    List.append(i)

print(sentence)

position = "Your word is found in position(s): "

keyword = input("Please enter a word you want to find the position of. ").upper()

times=0

for i in range (len(List)):
    if keyword in List[i]:
        i=i+1
        times=times+1
        found=str(i)
        position = position + found + " and "

if times==0:
    print("The word was not found.")
else:       
    print(position)

3 个答案:

答案 0 :(得分:1)

我会记录你在循环中找到字符串的位置,然后格式化它们。

假设您将found设为一个位置列表,并在循环中执行found.append(str(i)),然后在完成循环之后,执行以下操作:

if len(found) == 1:
    position += "{}".format(found[0])
else:
    # This will put a comma between everything except the last entry
    position += ", ".join(found[0:-1])
    # Then we add the last entry
    position += " and {}".format(found[-1])

答案 1 :(得分:1)

Python字符串有一个非常好的连接函数,可以帮助在列表项之间添加分隔符。因为你想添加"和"在最后一项之前,您可以使用连接加入除最后一项之外的所有项目并添加"添加"在添加最后一个之前......

这使得:

if not List:
    print("The word was not found.")
else:
    msg = "Your word is found in position(s): "
    if len(List) >  1:
        msg = msg + ', '.join([str(i) for i in List[:-1]]) + ' and '
    print(msg + str(List[-1]))

但是,您仍在使用position(s),这有点遗憾,您可以使用:

if not List:
    print("The word was not found.")
else:
    if len(List) >  1:
        print("Your word is found in positions:", ', '.join([str(i) for i in List[:-1]]), 'and ', str(List[-1]))
    else:
        print("Your word is found in position:", str(List[0]))

答案 2 :(得分:0)

  • 创建列表
  • 存储您找到该字词的所有位置。
  • 创建一个新的result字符串。
  • 迭代列表
  • 将每个单词附加到result字符串。
  • 如果您看到n - 1字,请追加and,否则追加,。如果您正在处理n字,请不要附加任何内容。
  • 最后,打印结果字符串。

这是通用编程方法。我很确定,会有一个优雅的python解决方案。

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
words = sentence.split(' ')

positions = []
print (sentence)
keyword = raw_input("Please enter a word you want to find the position of. ").upper()

i = 0
for i in range(len(words)):
  if keyword in words[i]:
    positions.append(i)

if len(positions):
  result = ''

  n = len(positions)

  i = 0
  while i < n:
    result += str(positions[i])
    if i == n - 2:
      result += ' and '
    elif i < n - 2:
      result += ', '
    i += 1
  print(result)

else:       
  print("The word was not found.")