【问题标题】:Printing parts of a string from a variable that can change从可以更改的变量中打印字符串的一部分
【发布时间】:2021-02-19 16:14:45
【问题描述】:

我试图弄清楚什么可能是非常简单的。我需要制作一个程序,在其中打印用户指定的城市并说明他们提供的信息。他们需要在输入语句中将其输入为 city,state 并且他们的答案存储在一个名为 userInput 的变量中。

现在,我的问题是:用户不会总是拥有相同的城市和州。因此,他们需要给出的字符串的索引号将会改变。我的问题是:无论它们在字符串中的位置如何,如何将这两件事分开打印?

编辑:这是我正在尝试做的一个示例:

userInput = input("Enter your city and state in the format city,state ")

程序应在一行打印“您居住在 [state the user types]”,在另一行打印“Your city is [city the user types>]”。

【问题讨论】:

标签: python string variables indexing slice


【解决方案1】:

使用str.split()函数在逗号处分割用户输入,并使用格式化字符串将值打印到行中:

city, state = input("Enter your city and state in the format city,state ").split(',')

print(f"You live in the state of {state}\nYour city is {city}")

【讨论】:

    【解决方案2】:

    如果用户总是使用逗号分隔符输入“city,state”,您可以使用split()

    user_input = input("Enter city,state  :")
    city, state = user_input.split(",")
    

    【讨论】:

      猜你喜欢
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 2018-05-09
      • 2021-06-25
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多