Python:是否有 BASIC 中的 mid、right 和 left 等价物?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22586286/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:13:14  来源:igfitidea点击:

Python: Is there an equivalent of mid, right, and left from BASIC?

pythonbasic

提问by pythonprogrammer

I want to do something like this:

我想做这样的事情:

    >>> mystring = "foo"
    >>> print(mid(mystring))

Help!

帮助!

采纳答案by Andy W

slices to the rescue :)

切片救援:)

def left(s, amount):
    return s[:amount]

def right(s, amount):
    return s[-amount:]

def mid(s, offset, amount):
    return s[offset:offset+amount]

回答by frnhr

If I remember my QBasic, right, left and mid do something like this:

如果我记得我的 QBasic,右、左和中,做这样的事情:

>>> s = '123456789'
>>> s[-2:]
'89'
>>> s[:2]
'12'
>>> s[4:6]
'56'

http://www.angelfire.com/scifi/nightcode/prglang/qbasic/function/strings/left_right.html

http://www.angelfire.com/scifi/nightcode/prglang/qbasic/function/strings/left_right.html

回答by Gareth Lock

These work great for reading left / right "n" characters from a string, but, at least with BBC BASIC, the LEFT$()and RIGHT$()functions allowed you to change the left / right "n" characters too...

这些非常适合从字符串中读取左/右“n”个字符,但是,至少在 BBC BASIC 中,LEFT$()RIGHT$()函数也允许您更改左/右“n”个字符......

E.g.:

例如:

10 a$="00000"
20 RIGHT$(a$,3)="ABC"
30 PRINT a$

Would produce:

会产生:

00ABC

Edit : Since writing this, I've come up with my own solution...

编辑:自从写这篇文章以来,我想出了我自己的解决方案......

def left(s, amount = 1, substring = ""):
    if (substring == ""):
        return s[:amount]
    else:
        if (len(substring) > amount):
            substring = substring[:amount]
        return substring + s[:-amount]

def right(s, amount = 1, substring = ""):
    if (substring == ""):
        return s[-amount:]
    else:
        if (len(substring) > amount):
            substring = substring[:amount]
        return s[:-amount] + substring

To return n characters you'd call

要返回您要调用的 n 个字符

substring = left(string,<n>)

Where defaults to 1 if not supplied. The same is true for right()

如果未提供,则默认为 1。right() 也是如此

To change the left or right n characters of a string you'd call

要更改您要调用的字符串的左侧或右侧 n 个字符

newstring = left(string,<n>,substring)

This would take the first n characters of substring and overwrite the first n characters of string, returning the result in newstring. The same works for right().

这将取 substring 的前 n 个字符并覆盖 string 的前 n 个字符,以 newstring 形式返回结果。对 right() 也一样。

回答by Stanton Attree

Thanks Andy W

谢谢安迪 W

I found that the mid() did not quite work as I expected and I modified as follows:

我发现 mid() 并没有像我预期的那样工作,我修改如下:

def mid(s, offset, amount):
    return s[offset-1:offset+amount-1]

I performed the following test:

我进行了以下测试:

print('[1]23', mid('123', 1, 1))
print('1[2]3', mid('123', 2, 1))
print('12[3]', mid('123', 3, 1))
print('[12]3', mid('123', 1, 2))
print('1[23]', mid('123', 2, 2))

Which resulted in:

这导致:

[1]23 1
1[2]3 2
12[3] 3
[12]3 12
1[23] 23

Which was what I was expecting. The original mid() code produces this:

这正是我所期待的。原来的 mid() 代码产生这个:

[1]23 2
1[2]3 3
12[3] 
[12]3 23
1[23] 3

But the left() and right() functions work fine. Thank you.

但是 left() 和 right() 函数工作正常。谢谢你。

回答by Stanton Attree

You can use this method also it will act like that

你可以使用这个方法,它也会像那样

thadari=[1,2,3,4,5,6]

#Front Two(Left)
print(thadari[:2])
[1,2]

#Last Two(Right)# edited
print(thadari[-2:])
[5,6]

#mid
mid = len(thadari) //2

lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]

Hope it will help

希望它会有所帮助

回答by Jim Sullivan

This is Andy's solution. I just addressed User2357112's concern and gave it meaningful variable names. I'm a Python rookie and preferred these functions.

这是安迪的解决方案。我刚刚解决了 User2357112 的问题,并给了它有意义的变量名。我是 Python 菜鸟,更喜欢这些功能。

def left(aString, howMany):
    if howMany <1:
        return ''
    else:
        return aString[:howMany]

def right(aString, howMany):
    if howMany <1:
        return ''
    else:
        return aString[-howMany:]

def mid(aString, startChar, howMany):
    if howMany < 1:
        return ''
    else:
        return aString[startChar:startChar+howMany]

回答by Scott

There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.

如果您正在寻找布尔结果,Python 中有用于“右”和“左”的内置函数。

str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True

right = str.endswith("test")
print(right)
> True