我想append
一个字符的字符串每三个字符 例如,如果我的字符串是NYCLHRNYC
后的结果将是NYC-LHR-NYC
字符串的长度总是3的Python:字符串操作
多我写了下面的代码:
x = raw_input("Enter the route")
print "Route: %s" %x
length = len(x)
print length
if length == 6:
newx= x[0:3] +"-"+ x[3:6]
elif length == 9:
newx= x[0:3] +"-"+ x[3:6] +"-"+ x[6:9]
elif length == 12:
newx= x[0:3] +"-"+ x[3:6] +"-"+ x[6:9] +"-"+ x[9:12]
elif length == 15:
newx= x[0:3] +"-"+ x[3:6] +"-"+ x[6:9] +"-"+ x[9:12]+"-"+ x[12:15]
elif length == 18:
newx= x[0:3] +"-"+ x[3:6] +"-"+ x[6:9] +"-"+ x[9:12]+"-"+ x[12:15]+"-"+ x[15:18]
elif length == 21:
newx= x[0:3] +"-"+ x[3:6] +"-"+ x[6:9] +"-"+ x[9:12]+"-"+ x[12:15]+"-"+ x[15:18]+"-"+ x[18:21]
print "After formattinng: %s" %newx
现在,这是做的非常机械的方式。在大多数情况下,我不知道字符串的最大长度。 有没有更好的方法来做到这一点for loop
或别的什么?
在此先感谢您的答案。
这么写的,用于格式化您的字符串(给方法的长度参数)的方法,并用位数学,你可以得到它的工作;) –