如何从Python中的字符串中删除前导和尾随空格?
例如:
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
Run Code Online (Sandbox Code Playgroud) 假设这是字符串:
The fox jumped over the log.
Run Code Online (Sandbox Code Playgroud)
这将导致:
The fox jumped over the log.
Run Code Online (Sandbox Code Playgroud)
什么是最简单的1-2衬垫可以做到这一点?没有分裂并进入列表......
可能重复:
在Python中用单个空格替换多个空格
如何在python中将多个空格压缩为1个空格?
例如,假设我有一个字符串
"some user entered text"
Run Code Online (Sandbox Code Playgroud)
我希望那成为
"some user entered text"
Run Code Online (Sandbox Code Playgroud) 我想知道如何删除字符串之间不需要的空格.例如:
>>> a = "Hello world"
Run Code Online (Sandbox Code Playgroud)
我想打印它删除多余的中间空格.
你好,世界
I'd like to shorten a string using textwrap.shorten or a function like it. The string can potentially have non-ASCII characters. What's special here is that the maximal width is for the bytes encoding of the string. This problem is motivated by the fact that several database column definitions and some message buses have a bytes based max length.
For example:
>>> import textwrap
>>> s = '? Ilsa, le méchant ? ? gardien ?'
# Available function that I …Run Code Online (Sandbox Code Playgroud) 可能重复:
在Python中用单个空格替换多个空格
试图弄清楚如何编写给定字符串的正则表达式:
"hi this is a test"
Run Code Online (Sandbox Code Playgroud)
我可以把它变成
"hi this is a test"
Run Code Online (Sandbox Code Playgroud)
将空格规范化为一个空格
有任何想法吗?非常感谢
在python中,我有例如以下字符串:
a = "Sentence with weird whitespaces"
Run Code Online (Sandbox Code Playgroud)
我想要相同的字符串,扩展的空格只用一个替换,所以最后的字符串会读取
'Sentence with weird whitespaces'
Run Code Online (Sandbox Code Playgroud)
我自己找到了一个解决方案,但有更好/更短的解决方案吗?
' '.join([x for x in a.split(' ') if len(x)>0])
Run Code Online (Sandbox Code Playgroud) 我正在检索表单中的大量数据
6800 MAIN ST
Run Code Online (Sandbox Code Playgroud)
如何格式化以使其看起来正常(数字和街道名称之间的一个空格),例如:
6800 MAIN ST
Run Code Online (Sandbox Code Playgroud)