简体   繁体   中英

How to split a string into two parts?

I am doing python exercises but I am stuck at one.

A string is divided in two parts(two new strings): part1 and part2.

If the length of the string is equal, then the two parts have to be equal as well.

Eg 'Help' = 'He' and 'lp'

If the length of the string is not equal, then the extra letter is assigned to part1.

Eg 'Hello' = 'Hel' and 'lo'

The exercise I am working on takes in two strings. I need to cut both these strings and then concatenate them in the following manner:

<String1 Part1> + <String2 Part2>

<String2 Part1> + <String1 Part2>

So if we have the words card and plan they become caan and plrd

So far all I can think of is:

def divide_strings(word1, word2):
    if len(word1)%2 > 0 or len(word2) %2 > 0:

    else len(word1) %2 == 0 or len(word2) %2 == 0:

I know I'm far from done, but I could really use a few hints in the right direction. My brain is stuck.

Thanks in advance!

You said hint -- so

The important thing in dividing the string is trying to figure out where to cut this string.

Consider this assignment

x = len(s) // 2

if len(s) is 0 or 1, x will be 0
if len(s) is 2 or 3, x will be 1
if len(s) is 4 or 5, x will be 2

In all cases, x will be the number of characters you want assigned to part2

Look up string slicing and note that it can take a negative index to count from the end of a string

ADDED

Also, I notice you examples do not seem to match your problem statement.

Ie, if the original string is "card", I would expect the result below based on your problem statement. Obviously, your show a different expected result -- probably a good idea to double check things.

a/ca b/rd

what you want is ceiling division:

>>> w = 'hello'
>>> split = -( ( -len(w) )//2 )
>>> split
3
>>> p1, p2 = w[:split], w[split:]
>>> p1
'hel'
>>> p2
'lo'

This is what split is:

  1. Take the len of the word (5)
  2. Take the negative of it (-5)
  3. Do Python's normal floor division, (-5//2 == -3)
  4. Then take the negative of that result, (3)

So do put this in a function:

def splitword(w):
    split = -((-len(w))//2)
    return w[:split], w[split:]

and

>>> splitword('help')
('he', 'lp')
>>> splitword('hello')
('hel', 'lo')

The following should help you out doing what you want. I don't have a python interpretter installed, so I couldn't in fact test this.

def splitword(w):
    split = -((-len(w))//2)
    return w[:split], w[split:]

part1a, part2a = splitword('card')
part1b, part2b = splitword('plan')

newword1 = part1a + part2b
newword2 = part1b + part2a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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