【发布时间】:2019-10-17 18:09:55
【问题描述】:
如何使用 Python 将字符添加到字符串中?例如,我喜欢在字符串中间添加一个“:”:09 和 00 之间的“0900”。
【问题讨论】:
标签: python-3.x
如何使用 Python 将字符添加到字符串中?例如,我喜欢在字符串中间添加一个“:”:09 和 00 之间的“0900”。
【问题讨论】:
标签: python-3.x
您可以使用slicing。
time = "0900"
time_with_colon = time[:2] + ":" + time[2:]
print(time_with_colon)
09:00
你不能改变一个字符串,但是你可以把它切片,得到索引前的一半字符串和索引后的一半。然后把两边和你想要的字符放在中间。
【讨论】:
_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。 (提示:两个数字相除会产生一个浮点值)。不过方法很好。请更正它,以便我可以投票
要将字符插入到您想要使用称为切片的特定位置。具体方法可以看这里: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)
【讨论】: