为什么\n没有被剥离字符串。拆分()

2024-04-24 19:59:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道为什么下面的第二个print语句没有删除输出中的\n,但是第一个print语句删除了。你知道吗

   str1 = "Line1-abcdef \nLine2-abc \nLine4-abcd \ndfsdf"
    print (str1.split( ))
    print (str1.split(' ', 2))

Tags: 语句splitabcprintabcdline1abcdefstr1
1条回答
网友
1楼 · 发布于 2024-04-24 19:59:46

.split()如果没有参数,则在运行任何连续的空白字符时将拆分。你知道吗

因此它会自动将“\n”视为单个2字符分隔符。你知道吗

.split(' ')使用一个参数,现在将在空格字符上拆分。你知道吗

发件人:https://docs.python.org/3.7/library/stdtypes.html#str.split

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

除了奖金:.split()没有参数可以确保:

  • 预剥离标记(无尾随或前导空格)
  • 没有''(空)或任何空白标记

这两个都是真正很好的节省时间。你知道吗

相关问题 更多 >