在没有 split() 函数的情况下打印字符串中的所有单词
Print all words in a String without split() function
我想在 Python 3.
中使用 split() 函数逐行 不使用 打印出字符串中的所有单词
短语是用户输入的str(input),它必须打印字符串中的所有单词,不管它是size.Here我的代码:
my_string = str(input("Phrase: "))
tam = len(my_string)
s = my_string
ch = " "
cont = 0
for i, letter in enumerate(s):
if letter == ch:
#print(i)
print(my_string[cont:i])
cont+=i+1
输出为:
短语:你好我的朋友
Hello
there
它只打印字符串中的两个单词,我需要它逐行打印所有单词。
抱歉,如果这不是家庭作业问题,但我会让您自己找出原因。
a = "Hello there my friend"
b = "".join([[i, "\n"][i == " "] for i in a])
print(b)
Hello
there
my
friend
一些您可以添加到流程中的变体,这些变体使用 if-else 语法无法轻松获得:
print(b.Title()) # b.lower() or b.upper()
Hello
There
My
Friend
def break_words(x):
x = x + " " #the extra space after x is nessesary for more than two word strings
strng = ""
for i in x: #iterate through the string
if i != " ": #if char is not a space
strng = strng+i #assign it to another string
else:
print(strng) #print that new string
strng = "" #reset new string
break_words("hell o world")
output:
hell
o
world
我想在 Python 3.
中使用 split() 函数逐行 不使用 打印出字符串中的所有单词短语是用户输入的str(input),它必须打印字符串中的所有单词,不管它是size.Here我的代码:
my_string = str(input("Phrase: "))
tam = len(my_string)
s = my_string
ch = " "
cont = 0
for i, letter in enumerate(s):
if letter == ch:
#print(i)
print(my_string[cont:i])
cont+=i+1
输出为:
短语:你好我的朋友
Hello
there
它只打印字符串中的两个单词,我需要它逐行打印所有单词。
抱歉,如果这不是家庭作业问题,但我会让您自己找出原因。
a = "Hello there my friend"
b = "".join([[i, "\n"][i == " "] for i in a])
print(b)
Hello
there
my
friend
一些您可以添加到流程中的变体,这些变体使用 if-else 语法无法轻松获得:
print(b.Title()) # b.lower() or b.upper()
Hello
There
My
Friend
def break_words(x):
x = x + " " #the extra space after x is nessesary for more than two word strings
strng = ""
for i in x: #iterate through the string
if i != " ": #if char is not a space
strng = strng+i #assign it to another string
else:
print(strng) #print that new string
strng = "" #reset new string
break_words("hell o world")
output:
hell
o
world