简体   繁体   English

使用Python中的字符串切片来查找字符串的前半部分长度?

[英]Finding the length of first half of a string using string slicing in Python?

I'm working on an assignment in PyCharm, and have been tasked with the following problem: 我正在PyCharm中进行作业,并且被分配了以下问题:

The len() function is used to count how many characters a string contains. len()函数用于计算一个字符串包含多少个字符。 Get the first half of the string storied in the variable 'phrase'. 获取存储在变量“短语”中的字符串的前半部分。

Note: Remember about type conversion. 注意:请记住有关类型转换的信息。

Here's my code so far that it's given me: 到目前为止,这是我得到的代码:

phrase = """
It is a really long string
triple-quoted strings are used
to define multi-line strings
"""

first_half = len(phrase)
print(first_half)

I have no idea what to do. 我不知道该怎么做。 I need to use string slicing to find the first half of the string "phrase". 我需要使用字符串切片来查找字符串“ phrase”的前半部分。 Any help appreciated. 任何帮助表示赞赏。 I apologize for my ignorance. 我为自己的无知表示歉意。

仅将字符串的前半部分切成薄片,请确保在字符串长度奇数的情况下使用// ,例如:

print phrase[:len(phrase) // 2] # notice the whitespace in your literal triple quote

Try something like: 尝试类似:

first_half = len(phrase)
print(phrase[0:first_half/2])

It will need to be smarter to handle strings of odd length. 处理奇数长度的字符串将需要更聪明。 See this question for more on slicing. 看到这个问题更多的切片。

first_half = phrase[:len(phrase)//2] or phrase[:int(len(phrase)/2)]

Note: Remember about type conversion. 注意:请记住有关类型转换的信息。

In Python 2 the division will yield an int, however in Python 3 you want to use an int division like this half = len(phrase) // 2 在Python 2中,该除法将产生一个int,但是在Python 3中,您希望使用一个int除法,例如half = len(phrase) // 2

Below is a Python 2 version 以下是Python 2版本

>>> half = len(phrase) / 2
>>> phrase[:half]
'\nIt is a really long string\ntriple-quoted st'

No need for the 0 in phrase[0:half] , phrase[:half] looks better :) phrase[0:half]不需要0phrase[:half]看起来更好:)

Try this print(string[:int(len(string)/2)]) 试试这个print(string[:int(len(string)/2)])

len(string)/2 returns a decimal normally so that's why I used int() len(string)/2通常返回一个十进制,所以这就是我使用int()的原因

Use slicing and bit shifting (which will be faster should you have to do this many times): 使用切片移位 (如果必须多次执行,则速度会更快):

>>> s = "This is a string with an arbitrary length"
>>> half = len(s) >> 1
>>> s[:half]
'This is a string wit'
>>> s[half:]
'h an arbitrary length'

Try this: 尝试这个:

phrase = """
It is a really long string
triple-quoted strings are used
to define multi-line strings
"""
first_half = phrase[0: len(phrase) // 2]
print(first_half)

you can simply slicing a string using it's indexes. 您可以简单地使用其索引对字符串进行切片。 For Example: 例如:

def first_half(str):
  return str[:len(str)/2]

The above function first_half accept a string and return it's half using slicing 上面的函数first_half接受一个字符串,并使用切片返回它的一半

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM