迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中检查字符串是否包含换行符 (\n)

作者:迹忆客 最近更新:2022/12/17 浏览次数:

使用 in 运算符检查字符串是否包含换行符,例如 if '\n' in string: 。 如果字符串包含换行符,则 in 运算符将返回 True,否则返回 False

string = 'fql\njiyik\ncom'

if '\n' in string:
    # 👇️ this runs
    print('The string contains a newline character')
else:
    print('The string does NOT contain a newline character')

print('\n' in 'fql\njiyik')  # 👉️ True

print('\n' in 'abcd')  # 👉️ False

Python 中检查字符串是否包含换行符

in 运算符测试成员资格。 例如,如果 x 是 s 的成员,则 x in s 的计算结果为 True,否则计算结果为 False

Python 中的换行符是:

  • \n 用于 POSIX 样式编码的文件
  • \r\n 用于 Windows 风格的编码文件
  • \r 用于旧的 Mac 编码文件

我们还可以检查字符串是否包含 \n\r 以涵盖所有编码。

string = 'fql\njiyik\ncom'

if '\n' in string or '\r' in string:
    # 👇️ this runs
    print('The string contains a newline character')
else:
    print('The string does NOT contain a newline character')


# 👇️ True
print('\n' in string or '\r' in string)

如果满足其中一个条件,则 or 运算符将返回 True

如果需要检查字符串是否以换行符结尾,可以使用 str.endswith() 方法。

# 👇️ True
print('jiyik\n'.endswith('\n'))

# 👇️ True
print('jiyik\r\n'.endswith(('\n', '\r', '\r\n')))

如果字符串以提供的后缀结尾,则 str.endswith 方法返回 True,否则该方法返回 False

endswith() 方法也可以传递一个字符串元组。

如果传递了一个元组,它会检查字符串是否以元组中的任何后缀结尾。

如果需要获取包含字符串中的行的列表,请使用 str.splitlines() 方法。

string = 'www\njiyik\ncom'

# 👇️ ['www', 'jiyik', 'com']
print(string.splitlines())

str.splitlines 方法在换行符处拆分字符串并返回包含字符串中的行的列表。

该方法不包括换行符,除非 keepends 参数设置为 True

string = 'fql\njiyik\ncom'

# 👇️ ['fql', 'jiyik', 'com']
print(string.splitlines())

# 👇️ ['fql\n', 'jiyik\n', 'com']
print(string.splitlines(True))

str.splitlines 方法在不同的线边界上分割,例如 \n\r\r\n

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便