如何从 Python 中的字符串中删除空格? [英] How to remove white spaces from a string in Python?
本文介绍了如何从 Python 中的字符串中删除空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从 python 中的字符串中删除空格.例如.
str1 = "TN 81 NZ 0025"str1sp = nospace(srt1)打印(str1sp)>>>TN81NZ0025
解决方案
使用 str.replace
:
要删除所有类型的空白字符,请使用 str.translate
:
I need to remove spaces from a string in python. For example.
str1 = "TN 81 NZ 0025"
str1sp = nospace(srt1)
print(str1sp)
>>>TN81NZ0025
解决方案
Use str.replace
:
>>> s = "TN 81 NZ 0025"
>>> s.replace(" ", "")
'TN81NZ0025'
To remove all types of white-space characters use str.translate
:
>>> from string import whitespace
>>> s = "TN 81 NZ\t\t0025\nfoo"
# Python 2
>>> s.translate(None, whitespace)
'TN81NZ0025foo'
# Python 3
>>> s.translate(dict.fromkeys(map(ord, whitespace)))
'TN81NZ0025foo'
这篇关于如何从 Python 中的字符串中删除空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文