我想在Python 3中使用split()函数逐行打印字符串中的所有单词而不是。
该短语是用户的str(输入),它必须打印字符串中的所有单词,无论它的大小。这是我的代码:
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
字符串中只打印两个单词,我需要它逐行打印所有单词。
答案 0 :(得分:0)
道歉,如果这不是一个家庭作业问题,但我会告诉你找出原因。
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
答案 1 :(得分:0)
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