【发布时间】:2013-11-18 13:06:11
【问题描述】:
首先,对不起我的英语不好。我是一个初学者程序员,我的 python 程序有一些问题。 我必须制作一个规范化空格和标点符号的程序,例如:
如果我把一个字符串叫做
" hello how, are u? "
新字符串必须是...
"Hello how are u"
但在我的代码中,结果是这样的,我不知道为什么:
"helloo how,, aree u??"
注意:我不能使用任何类型的函数,如 split()、strip() 等...
这是我的代码:
from string import punctuation
print("Introduce your string: ")
string = input() + " "
word = ""
new_word = ""
final_string = ""
#This is the main code for the program
for i in range(0, len(string)):
if (string[i] != " " and (string[i+1] != " " or string[i+1] != punctuation)):
word += string[i]
if (string[i] != " " and (string[i+1] == " " or string[i+1] == punctuation)):
word += string[i] + " "
new_word += word
word = ""
#This destroys the last whitespace
for j in range(0,len(new_word)-1):
final_string += new_word[j]
print(final_string)
谢谢大家。
编辑:
现在我有了这个代码:
letter = False
for element in my_string:
if (element != " " and element != punctuation):
letter= True
word += element
print(word)
但是现在,问题是我的程序无法识别标点符号,所以如果我输入:
"Hello ... how are u?"
必须像"Hellohowareu"
但它是这样的:
"Hello...howareu?
【问题讨论】:
-
你能用
translate吗? -
我不能使用任何函数或那个,我只能使用 string.punctuation 和基本代码,如 for、if、while 等......
-
但你想去掉字符串的开头和结尾?
-
是的,我不想在所有字符串的开头或结尾出现任何标点符号或空格
-
string[i+1] != [/==] punctuation将string[i+1]与整个punctuation字符串进行比较。那永远行不通。你想要string[i+1] in punctuation(如果punctuation是set,则更快),但要注意'是标点符号,所以像don't这样的词会很麻烦。
标签: python function space punctuation