Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. >>> import textwrap
  2. >>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
  3. >>> print(textwrap.fill(strs, 20))
  4. In my project, I
  5. have a bunch of
  6. strings that are
  7. read in from a file.
  8. Most of them, when
  9. printed in the
  10. command console,
  11. exceed 80 characters
  12. in length and wrap
  13. around, looking
  14. ugly.
  15.  
  16. >>> textwrap.fill?
  17.  
  18. Definition: textwrap.fill(text, width=70, **kwargs)
  19. Docstring:
  20. Fill a single paragraph of text, returning a new string.
  21.  
  22. Reformat the single paragraph in 'text' to fit in lines of no more
  23. than 'width' columns, and return a new string containing the entire
  24. wrapped paragraph. As with wrap(), tabs are expanded and other
  25. whitespace characters converted to space. See TextWrapper class for
  26. available keyword args to customize wrapping behaviour.
  27.  
  28. import re
  29.  
  30.  
  31. strs = """In my project, I have a bunch of strings that are.
  32. Read in from a file.
  33. Most of them, when printed in the command console, exceed 80.
  34. Characters in length and wrap around, looking ugly."""
  35.  
  36. print('n'.join(line.strip() for line in re.findall(r'.{1,40}(?:s+|$)', strs)))
  37.  
  38. # Reading a single line at once:
  39. for x in strs.splitlines():
  40. print 'n'.join(line.strip() for line in re.findall(r'.{1,40}(?:s+|$)', x))
  41.  
  42. In my project, I have a bunch of strings
  43. that are.
  44. Read in from a file.
  45. Most of them, when printed in the
  46. command console, exceed 80.
  47. Characters in length and wrap around,
  48. looking ugly.
  49.  
  50. lim=75
  51. for s in input_string.split("n"):
  52. if s == "": print
  53. w=0
  54. l = []
  55. for d in s.split():
  56. if w + len(d) + 1 <= lim:
  57. l.append(d)
  58. w += len(d) + 1
  59. else:
  60. print " ".join(l)
  61. l = [d]
  62. w = len(d)
  63. if (len(l)): print " ".join(l)
  64.  
  65. In my project, I have a bunch of strings that are read in from a file.
  66. Most of them, when printed in the command console, exceed 80 characters in
  67. length and wrap around, looking ugly.
  68.  
  69. I want to be able to have Python read the string, then test if it is over
  70. 75 characters in length. If it is, then split the string up into multiple
  71. strings, then print one after the other on a new line. I also want it to be
  72. smart, not cutting off full words. i.e. "The quick brown <newline> fox..."
  73. instead of "the quick bro<newline>wn fox...".
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement