簡體   English   中英

在 Python 中,如何用字符串切片?

[英]in Python, how do you slice with a string?

mystring = '[:3]'
x = mystring.split()
z = str(x).lstrip("['").rstrip("]'")
print(z)
print('hello'+int(z))

錯誤:ValueError:int() 的無效文字,基數為 10:':3'

如何通過使用 'mystring' 變量切片來制作 output 'hel'?

您可以使用exec exec()方法執行動態創建的程序,該程序可以是字符串,也可以是代碼 object。

>>> mystring = '[:3]'
>>> exec('print("hello"{})'.format(mystring))
hel

如果您想從用戶那里獲取 Python 代碼

>>> program = input('Enter a program:')
Enter a program:print("hello"[:3])
>>> exec(program)
hel

使用 exec() 時要小心 使用前請仔細閱讀文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM