使用 Robot Framework 时如何从字符串中修剪或去除空格
如果我有一个字符串“Hello How are you”,如何将其转换为“HelloHowareyou”(去除所有空格)
使用 Robot Framework 时如何从字符串中修剪或去除空格
如果我有一个字符串“Hello How are you”,如何将其转换为“HelloHowareyou”(去除所有空格)
${str.strip()} 也有效。它使用扩展变量语法示例:
*** Variables ***
${str}= ${SPACE}${SPACE}${SPACE}foo${SPACE}${SPACE}${SPACE}
*** Test cases ***
print string
log ${str} # will be printed with spaces around it
log ${str.strip()} # will be printed without spaces around it
使用 pybot -L TRACE 运行以查看传递给 log 关键字的内容。
${time_stamp}= Get Time
${time_stamp}= Evaluate '${time_stamp}'.replace(' ','_')
也可能有用
您可以使用 python 函数或使用正则表达式来执行此操作。
def Remove_Whitespace(instring):
return instring.strip()
| *Setting* | *Value* |
| Library | String
| Library | ./MyLibrary.py
| *Test Case* | *Action* | *Argument*
| T100 | [Documentation] | Removes leading and trailing whitespace from a string.
# whatever you need to do to get ${myString}
| | ${tmp}= | Remove Whitespace | ${myString}
# ${tmp} is ${myString} with the leading and trailing whitespace removed.
| T101 | [Documentation] | Removes leading and trailing whitespace from a string.
# whatever you need to do to get ${myString}
# The \ is needed to create an empty string in this format
| | ${tmp}= | Replace String Using Regexp | ${myString} | (^[ ]+|[ ]+$) | \
# ${tmp} is ${myString} with the leading and trailing whitespace removed.
最好的方法是使用纯 Robot Framework 关键字Remove String和Replace String这两个关键字在内部都使用了replace()函数,但使您的代码比其他选项更具可读性。此外,您可能还想查看RF v 3.0 中新增的Strip String
示例 1 -
${Result}= Remove String Hello How are you ${SPACE}
输出 1 -
示例 2 -
${Result2}= Replace String Hello How are you ${SPACE} ${EMPTY}
注意:${SPACE}、${EMPTY}是内置在机器人框架的变量中。