Python中空格上的拆分字符串

2024-09-27 07:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找与

String str = "many   fancy word \nhello    \thi";
String whiteSpaceRegex = "\\s";
String[] words = str.split(whiteSpaceRegex);

["many", "fancy", "word", "hello", "hi"]

Tags: hellostringhimanywordsplitfancywords
3条回答
import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)

使用split()将是对字符串进行拆分的最具Pythonic方式

记住,如果对没有空格的字符串使用split(),那么该字符串将在列表中返回给您

例如:

>>> "ark".split()
['ark']

没有参数的str.split()方法在空格上拆分:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']

相关问题 更多 >

    热门问题