我在一个小时前开始了这本速成教程,我正在做第一个“自己尝试”的活动,它让我做的是非常基本的事情,尽管我不知道如何获得正确的输出。我读过有关在变量中存储信息、打印该信息、从字符串中去掉空格以及使用\n和\t创建制表符的新行的内容。该活动要求“存储一个人的姓名,并在姓名的开头和结尾包含一些空格字符。确保每个字符组合"\t”和"\n“至少使用一次。打印姓名一次,以便显示姓名周围的空格。然后使用三个剥离函数中的每一个打印姓名: lstrip()、rstrip()和strip()。
full_name2 = " John Smith "
print(full_name2)
print("Whitespace Stripping:\n\t" + full_name2.rstrip())上面的代码给出了简单打印的正确输出:
Whitespace Stripping:
John Smith如何在第一行下面的两个后续新行中添加剩余的函数lstrip()和strip()来打印,结果如下所示:
Whitespace Stripping:
John Smith
John Smith
John Smith发布于 2016-01-12 09:40:01
与您使用rstrip的方式相同:
print("\t" + full_name2.lstrip())
print("\t" + full_name2.strip())要突出显示空格,您可以用引号将名称括起来:
print("\t'" + full_name2.lstrip() + "'")已更新
根据问题中的代码,上面的答案是最简单的方法。如果我这样做,我会使用变量并格式化一个多行字符串(为了可读性),如下所示:
full_name = " John Smith "
name_rstrip = full_name.rstrip()
name_lstrip = full_name.lstrip()
name_strip = full_name.strip()
print("""Whitespace Stripping:
\t'{name_rstrip}'
\t'{name_lstrip}'
\t'{name_strip}'""".format(**locals()))以下哪项输出:
Whitespace Stripping:
' John Smith'
'John Smith '
'John Smith'发布于 2016-01-12 09:43:51
我没有使用John Keyes的方法,而是将每个类型定义为一个变量,以便您以后可以使用它:
full_name2 = " John Smith "
rstrip = ("\t" + full_name2.rstrip())
lstrip = ("\t" + full_name2.lstrip())
strip = ("\t" + full_name2.strip())
print(full_name2)
print("Whitespace Stripping:\n\t" + rstrip + lstrip + strip)发布于 2016-09-09 19:10:52
变量"person“两边都有空格。使用".rstrip()“、".lstrip()”和“strain.()”可以删除空格。我输入了"Output:“,并使用"\t”将其(tab)移到右侧,以提高可读性。每个输出都打印在新行中(使用"\n")。
person = ' Mike Tyson '
print(person)
person_rstrip = person.rstrip()
person_lstrip = person.lstrip()
person_strip = person.strip()
print('\tOutput:\n'+ person_rstrip + '\n' + person_lstrip + '\n' + person_strip)结果是:Assignment 2.7, Chapter 2, Python Crash Course
https://stackoverflow.com/questions/34734195
复制相似问题