Python 逐字遍历字符串
我想知道如何逐字遍历字符串Python 逐字遍历字符串,python,Python,我想知道如何逐字遍历字符串 string = "this is a string" for word in string: print (word) 上面给出了一个输出: t h i s i s a s t r i n g 但我正在寻找以下输出: 这个 是 A. 一串 当您这样做时- for word in string: 您不是遍历字符串中的单词,而是遍历字符串中的字符。要遍历这些单词,首先需要使用str.split()将字符串拆分为单词,然后遍历这些单
string = "this is a string"
for word in string:
print (word)
上面给出了一个输出:
t
h
i
s
i
s
a
s
t
r
i
n
g
但我正在寻找以下输出:
这个
是
A.
一串
当您这样做时-
for word in string:
您不是遍历字符串中的单词,而是遍历字符串中的字符。要遍历这些单词,首先需要使用str.split()
将字符串拆分为单词,然后遍历这些单词。范例-
my_string = "this is a string"
for word in my_string.split():
print (word)
请注意,
str.split()
string = "this is a string"
ssplit = string.split()
for word in ssplit:
print (word)
输出:
使用
您可以使用来解析带有表情符号等的临时文本
s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)
输出:['hi'、'how'、'are'、'you']
与前面的问题(虽然不是完全重复的)关系非常密切。嘿,有没有办法维护所有的空格并做同样的事情?@MohitBhasi也许你搞错了str.split();不要期望每个人都知道它的作用或者你为什么使用它。我的评论很简短,但并不是侮辱。我只想做到最好。只有代码的答案很难阅读和理解,特别是对于那些“不知道”对你来说显而易见的东西的人。这就是为什么他们在这里寻找答案。
for word in string.split():
print word
from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize("This is a string.")
words_in_each_sentence = word_tokenize(sentences)
s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)