重新排序并向Strings添加内容

时间:2014-08-11 10:34:36

标签: python string

我是编码和Python的新手。有一件事,我无法通过谷歌找到一个满意的答案:我有一个STRING,并想重新排序并添加一些内容:

实施例

STRING的内容(绘制SVG-grafic的一些坐标):

STRING
M xy(1) xy(2) xy(3) C(1) xy(4) xy(5) xy(6) C(2) xy(7) xy(8) xy(9)

我想自动将其更改为: (将值复制到前面的'M',然后在前3对中设置一个新的'C')

STRING_new M xy(9) C3 xy(1) xy(2) xy(3) C(1) xy(4) xy(5) xy(6) C(2) xy(7) xy(8) xy(9)

至少我想返回String_new

我想这样做有复杂的操作,但我肯定是新手

那怎么做?

谢谢

2 个答案:

答案 0 :(得分:1)

也许最简单的方法是分离初始字符串中的所有元素,然后将它们连接起来。

例如:

string = 'M xy(1) xy(2) xy(3) C(1) xy(4) xy(5) xy(6) C(2) xy(7) xy(8) xy(9)'
list_element = string.split(' ')
new_string = '{0} {11}   C3 {1} {2} {3}   {4} {5} {6} {7}   {8} {9} {10} {11}'.format(*list_element)

将导致:

>>> new_string
'M xy(9)   C3 xy(1) xy(2) xy(3)   C(1) xy(4) xy(5) xy(6)   C(2) xy(7) xy(8) xy(9)'

但这不是一个非常灵活的解决方案,因为如果您的输入发生变化,一切都会出错。

答案 1 :(得分:0)

这会做你要求的,但结果中的C3应该是C(3)吗?

"""
Given a string like s, convert it so that the value after the initial m is replaced by the last value in the string.
This is followed by a new C tag (incremented over the final original C tag), and the rest of the original string 
beyond the M start tag is appended

s =     "M xy(1) xy(2) xy(3) C(1) xy(4) xy(5) xy(6) C(2) xy(7) xy(8) xy(9)"
new_s = "M xy(9) C3 xy(1) xy(2) xy(3) C(1) xy(4) xy(5) xy(6) C(2) xy(7) xy(8) xy(9)"
"""

import re


s =     "M xy(1) xy(2) xy(3) C(1) xy(4) xy(5) xy(6) C(2) xy(7) xy(8) xy(9)"

last_c = re.findall(r'C\((\d+)\)', s)[-1]
new_c = "C%s" % str(int(last_c) + 1)
my_list = s.split()
new_start = " ".join((my_list[0], my_list[-1]))
new_s = " ".join((new_start, new_c, s[1:]))
print new_s