【问题标题】:string .join method confusionstring .join 方法混淆
【发布时间】:2023-01-27 08:13:53
【问题描述】:

我尝试以两种方式加入示例字符串,首先通过代码输入,然后通过用户输入输入。我得到了不同的结果。

#为什么这些输出不一样(在 python 3.10.6 中):

sampleString = 'Fred','you need a nap! (your mother)'
ss1 = ' - '.join(sampleString)
print(ss1), print()

sampleString = input('please enter something: ')  #entered 'Fred'
ss2 = ' - '.join(sampleString)
print(ss2)

输出:

Fred - you need a nap! (your mother)

please enter something: 'Fred'
' - F - r - e - d - '

【问题讨论】:

    标签: python string join


    【解决方案1】:

    当你做

    sampleString = 'Fred','you need a nap! (your mother)'
    

    由于逗号,sampleString 是一个包含两个字符串的元组。当您加入它时,分隔符将放在元组的每个元素之间。所以它被放在字符串Fredyou need a nap! (your mother) 之间。

    当你做

    sampleString = input('please enter something: ')
    

    sampleString 是一个字符串。当您加入它时,分隔符将放在字符串的每个元素之间。所以它放在每个字符之间。

    如果在每种情况下都执行print(sampleString),您会看到这种差异。

    【讨论】:

      【解决方案2】:

      在第一种情况下,sampleString = 'Fred','you need a nap! (your mother)' 是由两个字符串组成的 tuple。当你join他们时,分隔符(-)被放在他们之间。

      在第二种情况下,sampleString 只是一个str,而不是一个元组。因此分隔符放置在字符串的每个元素(字符)之间。

      【讨论】:

        【解决方案3】:

        第一个代码块是使用字符串“-”作为分隔符连接元组 sampleString 的元素。在第二个代码块中,用户输入被视为单个字符串,因此 join() 方法尝试使用分隔符“-”连接字符串的字符。这就是输出不同的原因。如果您希望第二个代码块产生与第一个代码块相同的输出,您应该将用户输入更改为元组或字符串列表:

        sampleString = ('Fred', 'you need a nap! (your mother)')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多