user5079665
user5079665

Reputation:

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:

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.

Upvotes: 3

Views: 36482

Answers (8)

Codemaker2015
Codemaker2015

Reputation: 15638

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

Upvotes: 0

Alpha9
Alpha9

Reputation: 121

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)

Upvotes: 0

riki ruslan
riki ruslan

Reputation: 21

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

Upvotes: 1

kylieCatt
kylieCatt

Reputation: 11039

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'

Upvotes: 0

rassa45
rassa45

Reputation: 3560

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

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

Upvotes: 0

bakkal
bakkal

Reputation: 55448

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

Upvotes: 0

Malik Brahimi
Malik Brahimi

Reputation: 16711

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

Upvotes: 4

nalyd88
nalyd88

Reputation: 5148

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.

Upvotes: 1

Related Questions