替换字符串中的项目,Python

时间:2012-10-25 21:56:30

标签: python string replace

我正在尝试在python中定义一个函数来替换字符串中的某些项。我的字符串是一个字符串,包含度数分钟秒(即216-56-12.02)

我想替换破折号以便我可以得到正确的符号,所以我的字符串看起来像216°56'12.02“

我试过了:

def FindLabel ([Direction]):
  s = [Direction]
  s = s.replace("-","° ",1) #replace first instancwe of the dash in the original string
  s = s.replace("-","' ") # replace the remaining dash from the last string

  s = s + """ #add in the minute sign at the end

  return s

这似乎不起作用。我不确定出了什么问题。欢迎任何建议。

干杯, 麦克

2 个答案:

答案 0 :(得分:2)

老实说,我不打算替换。只需.split()

def find_label(direction):
    degrees, hours, minutes = direction.split('-')

    return u'{}° {}\' {}"'.format(degrees, hours, minutes)

如果你愿意,你可以更加浓缩它:

def find_label(direction):
    return u'{}° {}\' {}"'.format(*direction.split('-'))

如果您想修复当前的代码,请参阅我的评论:

def FindLabel(Direction):  # Not sure why you put square brackets here
  s = Direction            # Or here
  s = s.replace("-",u"° ",1)
  s = s.replace("-","' ")

  s += '"'  # You have to use single quotes or escape the double quote: `"\""`

  return s

您可能必须使用注释在Python文件的顶部指定utf-8编码:

# This Python file uses the following encoding: utf-8

答案 1 :(得分:1)

这就是我如何通过分成一个列表然后再加入来做到这一点:

s = "{}° {}' {}\"".format(*s.split("-"))