首页 文章

去除空白区域

提问于
浏览
-3

我想摆脱每一行末尾的空白区域 .

w = input("Words: ")
w = w.split()
k = 1
length = []
for ws in w:
  length.append(len(ws))
  y = sorted(length)
while k <= y[-1]:
  if k in length:
    for ws in w:
      if len(ws) != k:
        continue
      else:
        print(ws, end=" ")
    print("")
  k += 1

在评估长度时,输出是给我一些单词,例如,如果我输入我喜欢QI;我喜欢QI爱

但它在每一行的末尾都有空格 . 如果我尝试.rstrip()它我也删除单词之间的空格并得到;我真的很喜欢

3 回答

  • 0

    使用“”.join(ws)而它会自动但它们在同一行(你需要创建一个列表而不是一个字符串)

  • 0
    re.sub(r"[ ]*$","",x)
    

    您使用 re 模块的 re.sub .

  • 2

    你需要使用 rstrip
    演示:

    >>> 'hello '.rstrip()
    'hello'
    

    rstrip 从右边删除任何空格

    lstrip 从左侧删除空格:

    >>> '  hello '.lstrip()
    'hello '
    

    strip 从两端删除:

    >>> '  hello '.strip()
    'hello'
    

    你需要使用拆分将它们转换为列表

    >>> "hello,how,are,you".split(',')    # if ',' is the delimiter
    ['hello', 'how', 'are', 'you']
    >>> "hello how are you".split()       # if whitespace is delimiter
    ['hello', 'how', 'are', 'you']
    

相关问题