我有以下字符串:
mystring = '\n\nAvailability:\n Open source, \n\nResource Name:\n QIIME \n\nResource ID:\n SCR_008249'
我想替换上述字符串中的 \n,但不是 \n\n。
所以我尝试了这个:
new_string = " ".join(mystring.split())
发现了这个:
“可用性:开源,资源名称:QIIME,资源 ID:SCR_008249”
但我想要这样的东西:
'Availability: Open source,
Resource Name: QIIME Resource
ID: SCR_008249'
谢谢!
最佳答案
您可以使用正则表达式:
import re
print(re.sub(r'\n(\n)?', r'\1', mystring))
这解决了您所说的问题。但是,输出看起来与您的输出不同,因为您的输出不符合您的要求。
如果您还想标准化空白,请添加一些空白海绵模式,例如
print(re.sub(r'\n(\n)? *', r'\1 ', mystring))
关于python - 如何替换字符串中的 `\n` 而不是 Python 中的 `\n\n`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65111582/