我正在使用它来用逗号解码定界数组字符串:
formatted_string = re.sub('\s+', ', ', unknown_encoding_string[1:-1])
似乎可以使用它(注意到它后面仍然有逗号,但仍然可以使用)
unknown_encoding_string = "[-0.03833389 0.00832078 0.1206817 0.01020864
0.01418733 0.01334922 0.0180524 ]"
formatted_string = "-0.03833389, 0.00832078, 0.1206817, 0.01020864, 0.01418733, 0.01334922, 0.0180524,"
例如:https://pastebin.com/eSVj1K6Q
但与此不同。前面有“”,这会引起问题。
unknown_encoding_string = "[ -0.03833389 0.00832078 -5.50815463e-02
2.86253393e-02 -1.66405290e-02 2.03181207e-02]"
formatted_string = ", -0.03833389, 0.00832078, -5.50815463e-02, 2.86253393e-02, -1.66405290e-02, 2.03181207e-02"
eg: https://pastebin.com/UjswSVSs
我希望这样定界
"123,4342,54534"
我正在为此使用Python。
答案 0 :(得分:1)
Python有许多出色的工具可用于处理字符串,而无需求助于正则表达式。
unknown_encoding_string = "[-0.03833389 0.00832078 0.1206817 0.01020864 0.01418733 0.01334922 0.0180524 ]"
# Strip removes the specified characters from the start and end of the string
cleaned_string = unknown_encoding_string.strip("[] ")
# Split converts your string into a list of strings; by default splits on space
values = cleaned_string.split()
# Join will take an iterable and join it with the specified string as the joining character
formatted_string = ",".join(values)
# or in a single line...
formatted_string = ",".join(unknown_encoding_string.strip("[] ").split())
希望有帮助
答案 1 :(得分:0)
使用正则表达式,您可以在两个非空格字符之间插入逗号:
re.sub(r"(\S)\s+(\S)",r"\1, \2",text)
您可以将其与strip()组合:
re.sub(r"(\S)\s+(\S)",r"\1, \2",text.strip("[] "))
\ 1,\ 2等于括号中第1组和第2组中的匹配字符。
或者我们可以使用后向和前向:
re.sub(r"(?<=\S)\s+(?=\S)",r", ",text.strip("[] "))