2

I'm working on an assignment in PyCharm, and have been tasked with the following problem:

The len() function is used to count how many characters a string contains. 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". Any help appreciated. I apologize for my ignorance.

Community
  • 1
  • 1

8 Answers8

3

Just slice the first half of the string, be sure to use // in the event that the string is of odd length like:

print phrase[:len(phrase) // 2] # notice the whitespace in your literal triple quote
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
1

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.

Community
  • 1
  • 1
nalyd88
  • 4,940
  • 8
  • 35
  • 51
1
first_half = phrase[:len(phrase)//2] or phrase[:int(len(phrase)/2)]
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
0

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

Below is a Python 2 version

>>> 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 :)

bakkal
  • 54,350
  • 12
  • 131
  • 107
0

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

len(string)/2 returns a decimal normally so that's why I used int()

rassa45
  • 3,482
  • 1
  • 29
  • 43
0

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'
Community
  • 1
  • 1
kylieCatt
  • 10,672
  • 5
  • 43
  • 51
  • 2
    I feel like this is really pointless. Shifting right is the same as dividing by two. – Malik Brahimi Jul 11 '15 at 17:09
  • It gives you the same result but it does work faster. If the OP (or any future readers) need to perform an operation like this millions of times it will be faster than using division. – kylieCatt Jul 11 '15 at 17:22
0

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)
Alpha9
  • 101
  • 7
0

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

Codemaker2015
  • 12,190
  • 6
  • 97
  • 81