Wednesday, 15 May 2013

How can I split a string in Python after a specific character count? -



How can I split a string in Python after a specific character count? -

i apologize if duplicate can't seem find out there involves splitting string based on character count. example, let's have next string:

lorem ipsum dolor sit down amet, consectetur adipiscing elit. sed ullamcorper, eros sed porta dapibus, nunc nibh iaculis tortor, in rhoncus quam orci sed ante. sed ac dictum nibh.

now, can split string based on specific character, how can split string after nth character, regardless of is? this, working syntax thinking:

max_char = n #where n number of characters split after mytext = 'user input string. @ to the lowest degree paragraph long.' char_count = len(mytext) if char_count > max_char: #split string @ max_char, create variables: mytext1 , mytext2

any help appreciated. thanks!

update

i wanted post update since question approached half of problem. martijin's reply below sliced string above. however, since string making edits user submitted, ran problem of slicing words in half. in order prepare problem, used combination of rsplit , rstrip break paragraph correctly. in case out there facing same issues me here code used create work:

line1 = note[:36] line2 = note[36:] if not line1.endswith(' ', 1): line2_2 = line1.rsplit(' ')[-1] line1_1 = line1.rstrip(line2_2) line2_2 = line2_2 + line2 line1 = '' line2 = ''

now, i'm sure there more efficient/elegant way of doing this, still works can benefit it. thanks!

you looking slicing:

mytext1, mytext2 = mytext[:max_char], mytext[max_char:]

python strings sequences, select first max_char characters, utilize piece select those, , sec half select starting @ max_char until end.

this covered in python tutorial well.

python

No comments:

Post a Comment