我正在尝试删除字符串末尾的空格。
例如,如果我有一个字符串
"text3 "
我想删除最后一个空格,以便我的字符串最终为 "text3"
.
到目前为止,我已经尝试过使用这个方法
${space_character} = Set Variable ${SPACE}
${desired_text} = Remove String ${desired_text}
${space_character}
${desired_text}
最初只是"text3 "
。这似乎并没有删除空间。此外,我只想消除最后的空格字符,而不是中间的任何字符,因为我可以有一个 ${desired_text}
等于 "this is an example "
之类的东西。最后的空格是我要删除的,只留下"this is an example"
.
Robot Framework基于Python,字符串变量可以直接使用Python函数/方法
在 python 中,我们有
lstrip()
:从左边删除字符,rstrip()
:从右边删除字符,以及 strip()
:从左边和右边删除字符。
要删除的默认字符是空格。
您案例的使用示例是:
${desired_text}= Set Variable ${desired_text.rstrip()}
带有
rstrip()
的另一个答案是完全正确的,这是修剪任何空白的正确方法。
如果情况是 (特殊情况) 只需要删除一个空格,这可以通过一些基本的 python 技巧来完成 - 检查最后一个字符是空格,如果是这样 - 将变量重新分配给它的值没有最后的字符。
由于 python 中的字符串被视为字符列表,因此您可以对它们进行寻址和切片。列表索引操作符(
[]
)支持指向“列表的最后一个元素”([-1]
)的指针,切片支持“返回从头到尾的所有内容”([:-1]
).
IF """${my string}"""[-1] == ' '
${my string}= Set Variable ${my string}[:-1]
END
# alternatively, on a single line:
${my string}= Set Variable If """${my string}"""[-1] == ' ' ${my string}[:-1]
... ${my string} # this is the "else" condition, e.g. what will be assigned of the last char is not a space - the variable's value w/o modification
使用 Replace String Using Regexp 关键字
${new_text}= String.Replace String Using Regexp ${old_text} \\s+ ${EMPTY}
例子
*** Settings ***
Library String
*** Test Cases ***
TEST
${old_text}= Set Variable "TEST NAJA "
Log ${old_text}
${new_text}= String.Replace String Using Regexp ${desired_text} \\s+ ${EMPTY}
Log ${new_text}