返回介绍

Strings and String Handling

发布于 2025-02-25 23:43:35 字数 1308 浏览 0 评论 0 收藏 0

One of the most important features of Python is its powerful and easy handling of strings. Defining strings is simple enough in most languages. But in Python, it is easy to search and replace, convert cases, concatenate, or access elements. We’ll discuss a few of these here. For a complete list, see: http://www.tutorialspoint.com/python/python_strings.htm

a = "A string of characters, with newline \n CAPITALS, etc."
print(a)
b=5.0
newstring = a + "\n We can format strings for printing %.2f"
print(newstring %b)

Now let’s try some other string operations:

a = "ABC DEFG"
print(a[1:3])
print(a[0:5])

There are several things to learn from the above. First, Python has associated an index to the string. Second the indexing starts at 0, and lastly, the upper limit again means ‘up to but not including’ (a[0:5] prints elements 0,1,2,3,4).

a = "ABC defg"
print(a.lower())
print(a.upper())
print(a.find('d'))
print(a.replace('de','a'))
print(a)
b = a.replace('def','aaa')
print(b)
b = b.replace('a','c')
print(b)
b.count('c')

This is fun! What else can you do with strings in Python? Pretty much anything you can think of!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文