给定整数参数Python时的字符串操作 [英] String manipulation when given an integer parameter Python
本文介绍了给定整数参数Python时的字符串操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理SVG文件. 我将此字符串作为样式
I am manipulating an SVG file. I have this string as a style
'.cls-1{fill:#755841;}.cls-2{fill:#f7c394;}.cls-3{fill:#9b7657;}.cls-
4{fill:#7f6145;}.cls-5{fill:#ffc9a1;}.cls-6{fill:#ffcd98;}.cls-
7{fill:#3d0c0c;}.cls-8{fill:#fff;}.cls-9{fill:#313cc4;}'
我想创建一个接收输入说14的函数,并将此字符串更改为从输入连续的数字开始.例如,这里的课程将从14 + 1 = 15开始,依此类推:
I want to create a function that receives an input say 14 and changes this string to start at a number that is continuing from the input. For example here classes will start from 14 + 1 = 15 and so on:
'.cls-15{fill:#755841;}.cls-16{fill:#f7c394;}.cls-17{fill:#9b7657;}.cls-
18{fill:#7f6145;}.cls-19{fill:#ffc9a1;}.cls-20{fill:#ffcd98;}.cls-
21{fill:#3d0c0c;}.cls-22{fill:#fff;}.cls-23{fill:#313cc4;}'
不太确定哪种方法最好.是正则表达式吗?
Not really sure what will be the best approach. Is it regex?
推荐答案
嗯,字符串实际上是CSS代码.如何使用python CSS解析器解析它,然后实用地访问生成的对象?
Well, the string is actually CSS code. How about parsing it with a python CSS parser and then access the resulting objects pragmatically?
使用 cssutils :链接
import cssutils
css = '.cls-1{fill:#755841;}.cls-2{fill:#f7c394;}.cls-3{fill:#9b7657;}.cls-4{fill:#7f6145;}.cls-5{fill:#ffc9a1;}.cls-6{fill:#ffcd98;}.cls-7{fill:#3d0c0c;}.cls-8{fill:#fff;}.cls-9{fill:#313cc4;}'
sheet = cssutils.parseString(css)
for rule in sheet:
text = rule.selectorText.split('-')
name,num = text
num = int(num)
num += 10
rule.selectorText = name + '-' + str(num)
print sheet.cssText.translate(None, ' \n\t\r')
输出:
.cls-11{fill:#755841}.cls-12{fill:#f7c394}.cls-13{fill:#9b7657}.cls-14{fill:#7f6145}.cls-15{fill:#ffc9a1}.cls-16{fill:#ffcd98}.cls-17{fill:#3d0c0c}.cls-18{fill:#fff}.cls-19{fill:#313cc4}
这篇关于给定整数参数Python时的字符串操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文