Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.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
在Python上不带空格地每隔打印一个字符串的字母_Python_String - Fatal编程技术网

在Python上不带空格地每隔打印一个字符串的字母

在Python上不带空格地每隔打印一个字符串的字母,python,string,Python,String,我试图构建一个函数,该函数将接受一个字符串并打印该字符串的每一个字母,但它必须没有空格 例如: def PrintString(string1): for i in range(0, len(string1)): if i%2==0: print(string1[i], sep="") PrintString('My Name is Sumit') 它显示输出: M a e i u i 但我不想要空间。任何帮助都将

我试图构建一个函数,该函数将接受一个字符串并打印该字符串的每一个字母,但它必须没有空格

例如:

def PrintString(string1):
    for i in range(0, len(string1)):
        if i%2==0:
            print(string1[i], sep="")

PrintString('My Name is Sumit')
它显示输出:

M
 
a
e
i
 
u
i

但我不想要空间。任何帮助都将不胜感激。

您始终可以为它创建一个快速函数,只需将空格替换为空字符串即可。 范例


有很多不同的方法来解决这个问题。在我看来,这个线程很好地解释了这一点:

使用步长
string1[::2]
迭代字符串中的每2个字符,如果是


执行循环之前,请删除所有空格

而且不需要在循环中测试
i%2
。使用每隔一个字符返回一个片段

def PrintString(string1):
    string1 = string1.replace(' ', '')
    print(string1[::2])

替换所有空格并获取其他字母

def PrintString(string1):
  return print(string1.replace(" ", "") [::2])

PrintString('My Name is Sumit')

这取决于您是要先删除空格,然后拾取每一个字母,还是将每一个字母打印出来,除非它是空格:

s = "My name is Summit"
print(s.replace(" ", "")[::2])
print(''.join([ch for ch in s[::2] if ch != " "]))
印刷品:

MnmiSmi
Maeiumt

这不会打印其他所有字符,它会打印所有不是空格的字符。和我的一样,但也是最好的!不清楚您是不想在输出中使用空格,还是只想在拾取其他每个字符之前忽略空格。我不想在输出中使用空格然后只更新
if
中的条件以反映您不想打印的内容,例如,如果I%2==0和string1[I]!='':这是否回答了您的问题<代码>sep=“”在代码中不执行任何操作。你是说
end=”“
s = "My name is Summit"
print(s.replace(" ", "")[::2])
print(''.join([ch for ch in s[::2] if ch != " "]))
MnmiSmi
Maeiumt