search

Home  >  Q&A  >  body text

Python basic knowledge quick questions

s = 'w w'
s.strip() # 为什么去除不了中间的空格

s = 'w w'
s.replace('\s',';') # 为什么替换不了,\s 表示空格没错吧。。

In fact, the final requirement is this:
means that (multiple) spaces, (multiple) line feeds, (multiple) carriage returns and other whitespace characters will appear in the middle and on both sides of the string. I want to convert these whitespace characters. into ";", is there any good way

大家讲道理大家讲道理2745 days ago674

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-24 11:36:52

    Strip removes the spaces at the left and right ends, but the spaces in the middle cannot be removed.
    replace cannot use regular expressions as parameters, you must use the re module.

    import re
    re.sub('\s+', ';', 'w w')

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-24 11:36:52

    replace is used to replace one string with another string. For it, s is an ordinary string and has no other meaning.

    For your needs, I think you can use str.maketrans and translate functions to achieve it.

    My running environment is python3.5, the example is as follows:
    s = 'w w'
    transmap=str.maketrans({' ':';','r':';','n':';' })
    print( s.translate(transmap) )

    Run result:
    w;w

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-24 11:36:52

    Actually ";".join(s.split()) is fine

    reply
    0
  • Cancelreply