Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
打印不带空格的结果python3_Python_Python 3.x_Printing - Fatal编程技术网

打印不带空格的结果python3

打印不带空格的结果python3,python,python-3.x,printing,Python,Python 3.x,Printing,结果: def WhichAreCaps(Word): for w in Word: if w.isupper() == True: print (w) WhichAreCaps("IJkdLenMd") 所以我试图构建一个代码,在字符串中找到大写字母并打印出这些字母。问题是我希望结果显示为一行字符串,而不是四行。有没有办法做到这一点?(我只是个初学者;)print函数接受一个end关键字参数来指定打印后字符串的结尾。默认情况下,它设置为新行(\n

结果:

def WhichAreCaps(Word):
    for w in Word:
        if w.isupper() == True:
          print (w)

WhichAreCaps("IJkdLenMd")

所以我试图构建一个代码,在字符串中找到大写字母并打印出这些字母。问题是我希望结果显示为一行字符串,而不是四行。有没有办法做到这一点?(我只是个初学者;)

print
函数接受一个
end
关键字参数来指定打印后字符串的结尾。默认情况下,它设置为新行(
\n
),您只需使用空格即可。还要注意的是,检查任何表达式的truths值时使用
==True
是错误的,因为
True
解释为1,返回1的所有内容都将解释为True。如果w.isupper(),您只需使用

另一种方法是
在函数中生成元音并使其成为生成器:

def WhichAreCaps(Word):
    for w in Word:
        if w.isupper():
          print(w, end=' ')
然后,您可以以任何喜欢的方式加入结果并打印它:

def WhichAreCaps(Word):
    for w in Word:
        if w.isupper():
            yield w
毕竟,对于这个问题,作为一种更具python风格的方法,您可以简单地在
str.join
中使用列表理解:

print(','.join(WhichAreCaps(Word))) 

您只需将字母附加到空字符串,然后返回它

print(' '.join([w for w in Word if w.isupper()]))

您可以
'.join(..)
将字符连接在一起…请参阅文档(尤其是
end
参数)。@WillemVanOnsem我尝试过打印(“.join(w)),但问题仍然相同。顺便说一句,如果函数将结果作为字符串返回而不是打印它们,那么它会更有用。这样,调用方可以自己打印结果,或者在打印结果之前对结果进行其他处理。@ChikkinMan更改方法:
“”。join(如果c.isupper(),则在word中用c代替c)
。我会在返回之前用一个空的
print()
来清理它。@Ev.Kounis谢谢。@Kasramvd Yup,使用了end=“”,它成功了。!非常感谢。我不懂dv。。投票人能解释一下吗?@Ev.Kounis也许这是因为这是一个只有密码的答案。或者可能是被否决的选民对答案的早期版本进行了投票,该版本使用了Python2
print
语句,但没有注意到Akshay解决了这个问题。谢谢大家。我对这一点比较陌生。我投了反对票,因为1)这是一个只使用代码的答案,2)
==True
是多余的,而且大多数情况下3)我不允许字符串串联,因为它性能不佳。
print(' '.join([w for w in Word if w.isupper()]))
def WhichAreCaps(Word):
    ans=''
    for w in Word:
        if w.isupper() == True:
          ans+=w
    print(ans)