似乎可以在 python 中找到子字符串函数。
假设我想在一个字符串中输出前100个字符,我该如何做呢?
我希望这样做也是安全的,这意味着如果字符串是50个字符,它不应该失败。
print my_string[0:100]
简单:
print mystring[:100]
From Python 教程:
处理退化的切片指数 优雅地: < strong > 一个太大的索引 被字符串 size 替换为 上界小于下界 则返回一个空字符串。
因此,使用 x[:100]是安全的。
x[:100]
Slicing of arrays is done with [first:last+1].
[first:last+1]
我经常使用的一个技巧是用省略号来表示额外的信息。因此,如果您的字段是100个字符,我将使用:
if len(s) <= 100: print s else: print "%s..."%(s[:97])
是的,我知道 ()在这种情况下对于 %格式运算符来说是多余的,这就是我的风格。
()
%
To answer Philipp's concern ( in the comments ), slicing works ok for unicode strings too
>>> greek=u"αβγδεζηθικλμνξοπρςστυφχψω" >>> print len(greek) 25 >>> print greek[:10] αβγδεζηθικ
如果您希望以脚本的形式运行上面的代码,请将这一行放在顶部
# -*- coding: utf-8 -*-
如果您的编辑器没有在 utf-8中保存,请替换正确的编码
以前的大多数示例都会在字符串不够长的情况下引发异常。
另一种方法是使用 'yourstring'.ljust(100)[:100].strip().
'yourstring'.ljust(100)[:100].strip()
这会给你前100个字符。 如果字符串的最后一个字符是空格,那么可能会得到一个较短的字符串。
使用 %进行字符串格式化是处理这个问题的好方法。
格式化代码 '%s'将 '12345'转换为字符串,但它已经是一个字符串。
'%s'
'12345'
>>> '%s' % '12345' '12345'
'%.3s'指定只使用前三个字符。
'%.3s'
>>> '%.3s' % '12345' '123'
'%.7s'说要使用前七个字符,但是只有五个,没问题。
'%.7s'
>>> '%.7s' % '12345' '12345'
'%7s' uses up to seven characters, filling missing characters with spaces on the left.
'%7s'
>>> '%7s' % '12345' ' 12345'
'%-7s'是同样的东西,除了填充右边缺少的字符。
'%-7s'
>>> '%-7s' % '12345' '12345 '
'%5.3'表示使用前三个字符,但在左侧填充空格,使其总共为五个字符。
'%5.3'
>>> '%5.3s' % '12345' ' 123'
Same thing except filling on the right.
>>> '%-5.3s' % '12345' '123 '
也可以处理多个参数!
>>> 'do u no %-4.3sda%3.2s wae' % ('12345', 6789) 'do u no 123 da 67 wae'
如果您需要更大的灵活性,也可以使用 str.format()。
str.format()
[start:stop:step]
因此,如果你想只取100个第一个字符,使用 your_string[0:100]或 your_string[:100] 如果希望只取偶数位置的字符,请使用 your_string[::2] Start、 stop-len 和 step-1的“默认值”为0。因此,当您没有提供其中的一个并放置“ :”时,它将使用它的默认值。
your_string[0:100]
your_string[:100]
your_string[::2]