9

使用 Robot Framework 时如何从字符串中修剪或去除空格

如果我有一个字符串“Hello How are you”,如何将其转换为“HelloHowareyou”(去除所有空格)

4

4 回答 4

21

${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 关键字的内容。

于 2013-07-30T13:07:09.183 回答
4
${time_stamp}=       Get Time
${time_stamp}=       Evaluate    '${time_stamp}'.replace(' ','_')

也可能有用

于 2016-09-28T21:14:38.633 回答
3

您可以使用 python 函数或使用正则表达式来执行此操作。

我的图书馆.py

def Remove_Whitespace(instring):
    return instring.strip()

我的套件.txt

| *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.
于 2013-07-24T15:52:42.697 回答
1

最好的方法是使用纯 Robot Framework 关键字Remove StringReplace 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}

输出 2 -
在此处输入图像描述

注意:${SPACE}、${EMPTY}是内置在机器人框架的变量中。

于 2020-08-26T18:24:21.087 回答