Python作业,中点和舍入字符串

时间:2019-02-09 00:17:40

标签: python

这些是我的教授给出的步骤,

  1. 假设用户将输入至少包含1个字符的字符串
  2. 将输入存储为user_input
  3. 计算用户输入的长度
  4. 将其存储为“字符串长度”
  5. 打印消息,说明长度是偶数还是奇数 6.打印“ length is”和字符串的长度
  6. 假设用户将输入“ h1”,“ div”或“ article”
  7. 将此输入存储为变量“标签”

  8. 计算器长度为string_length的一半,四舍五入

  9. 将此值存储为“中点”
  10. 使用中点计算一个新字符串,该字符串是“ user_input”的前半部分
  11. 将其存储为“ first_half”

  12. 以以下格式first_half

  13. 计算一个新字符串,该字符串是'tag'和'first_half'的串联
  14. 将此值存储在一个名为“ tagd_input”的变量中。

随附的是我已经运行的代码。一切正常,直到我开始定义“ tag”变量。所以基本上在第9步及以后,我遇到了问题。

user_input=input ("Please enter something")
string_length=len(user_input)
even_message= string_length % 2

if even_message>0:
print ("The length is", string_length, "characters long and is 
odd.")

else:
print ("Your length is", string_length, "characters long and is 
even.")

tag= input("Input one of the following: h1, div or article.")

midpoint = (string_length/2)
first_half= (midpoint)
tagged_input= print ((tag) + (midpoint) + "/" + (tag))

输出应该是这个。 (将屏幕截图上传到imgur)

https://imgur.com/a/ogiTQiH

1 个答案:

答案 0 :(得分:1)

这应该可以工作(用此代码替换代码的最后3行):

midpoint = (string_length//2)
first_half = user_input[:midpoint]
tagged_input = f"<{tag}>{first_half}</{tag}>"

(1)第一行使用 // 运算符,该运算符进行除法和四舍五入

(2)第二行使用列表/序列切片:Understanding slice notation

(3)第三行使用python的一个相当新且非常有用的功能,称为f-strings:https://realpython.com/python-f-strings/