如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
当前回答
"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'
或者你可以用regexp变得更古怪
其他回答
如果您的问题是清除多行str对象(oldstr)中的所有换行符,您可以根据分隔符“\n”将其拆分为一个列表,然后将此列表合并为一个新的str(newstr)。
newstr=“”.jjoin(oldstr.split('\n'))
我不使用Python编程,但我在Python.org上遇到了一个常见问题解答,建议使用Python 2.2或更高版本的S.rstrip(“\r\n”)。
"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'
或者你可以用regexp变得更古怪
您可以使用strip:
line = line.strip()
演示:
>>> "\n\n hello world \n\n".strip()
'hello world'
s = '''Hello World \t\n\r\tHi There'''
# import the module string
import string
# use the method translate to convert
s.translate({ord(c): None for c in string.whitespace}
>>'HelloWorldHiThere'
使用正则表达式
s = ''' Hello World
\t\n\r\tHi '''
print(re.sub(r"\s+", "", s), sep='') # \s matches all white spaces
>HelloWorldHi
替换\n,\t,\r
s.replace('\n', '').replace('\t','').replace('\r','')
>' Hello World Hi '
使用正则表达式
s = '''Hello World \t\n\r\tHi There'''
regex = re.compile(r'[\n\r\t]')
regex.sub("", s)
>'Hello World Hi There'
使用Join
s = '''Hello World \t\n\r\tHi There'''
' '.join(s.split())
>'Hello World Hi There'