【问题标题】:Insert a character to a string with Python [duplicate]使用Python将字符插入字符串[重复]
【发布时间】:2019-10-17 18:09:55
【问题描述】:

如何使用 Python 将字符添加到字符串中?例如,我喜欢在字符串中间添加一个“:”:09 和 00 之间的“0900”。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您可以使用slicing

    time = "0900"
    time_with_colon = time[:2] + ":" + time[2:]
    print(time_with_colon)
    

    09:00

    你不能改变一个字符串,但是你可以把它切片,得到索引前的一半字符串和索引后的一半。然后把两边和你想要的字符放在中间。

    【讨论】:

      【解决方案2】:
      _input = '0900'
      input_to_list = list(_input)
      input_to_list.insert(round(len(input_to_list)/2), ':')
      _input_updated = "".join(input_to_list)
      

      【讨论】:

      • 这也引起了我的注意!您的代码中有一个错误:TypeError: integer argument expected, got float。 (提示:两个数字相除会产生一个浮点值)。不过方法很好。请更正它,以便我可以投票
      • @Simon 感谢您指出这个错误,我已经更新了代码。现在我认为完全忘记 python2 是件好事 :)
      【解决方案3】:

      要将字符插入到您想要使用称为切片的特定位置。具体方法可以看这里:Add string in a certain position in Python

      假设你总是想要插入到一个不同长度的字符串的中间,那么只要字符的总和是偶数,这将起作用(要清楚你拥有的字符的总和提供的是 4)。然后以下将正常工作:

      string = "0099"
      pos = int(len(string)/2)
      new = string[:pos] + ":" + string[pos:]
      print(new)
      

      但是,如果您的字符串不是偶数,这将不起作用,当所有字符加在一起时,: 将出现在错误的位置。

      遗憾的是,仅在十进制值上使用int() 不会对其进行四舍五入,它仅通过删除任何浮点值将其转换为整数。如本例所示:

      >>> int(3.9)
      3
      

      您可能想使用round() 函数:

      pos = round(len(string)/2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 1970-01-01
        • 2016-09-12
        • 1970-01-01
        • 2020-02-02
        • 2011-03-22
        相关资源
        最近更新 更多