在 python 中打印字符串的特定部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23354115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing specific parts of a string in python
提问by user3586691
def PrintThree(s):
x = len(s)
return s[0:3] + x[3:]
I am pretty stuck right now on how to print only certain parts of a string. I am trying to make a code where python will print 3 characters at a time, I am trying to make it so the code prints out the whole string but only shows three characters at a time.
我现在很困惑如何只打印字符串的某些部分。我正在尝试编写一个代码,其中 python 将一次打印 3 个字符,我正在尝试使代码打印出整个字符串,但一次只显示三个字符。
This should work with a string of any length.
这应该适用于任何长度的字符串。
回答by A.J. Uppal
Use slicing:
使用切片:
def PrintThree(string):
return string[:3]
This runs as:
这运行为:
>>> PrintThree('abcde')
'abc'
>>> PrintThree('hello there')
'hel'
>>> PrintThree('this works!')
'thi'
>>> PrintThree('hi')
'hi'
>>>
In the last example, if the length is less than 3, it will print the entire string.
在最后一个例子中,如果长度小于 3,它将打印整个字符串。
string[:3]
is the same as string[0:3]
, in that it gets the first three characters of any string. As this is a one liner, I would avoid calling a function for it, a lot of cuntions gets confusing after some time:
string[:3]
与 相同string[0:3]
,因为它获取任何字符串的前三个字符。由于这是一个单行,我会避免为它调用一个函数,一段时间后很多功能会变得混乱:
>>> mystring = 'Hello World!'
>>> mystring[:3]
'Hel'
>>> mystring[0:3]
'Hel'
>>> mystring[4:]
'o World!'
>>> mystring[4:len(mystring)-1]
'o World'
>>> mystring[4:7]
'o W'
>>>
Or, if you want to print every three characters in the string, use the following code:
或者,如果要打印字符串中的每三个字符,请使用以下代码:
>>> def PrintThree(string):
... string = [string[i:i+3] for i in range(0, len(string), 3)]
... for k in string:
... print k
...
>>> PrintThree('Thisprintseverythreecharacters')
Thi
spr
int
sev
ery
thr
eec
har
act
ers
>>>
This uses list comprehensionto split the string for every 3 characters. It then uses a for
statement to print each item in the list.
这使用列表理解将字符串拆分为每 3 个字符。然后使用for
语句打印列表中的每个项目。
回答by Ivan Nevostruev
I'll try to guess expected result:
我会试着猜测预期的结果:
def printThree(str):
for i in range(0, len(str), 3):
print str[i:i+3]
Output
输出
>>> printThree("somestring")
som
est
rin
g