0

I want to copy whitespace like spaces and tabs from string to string in Python 2. For example if I have a string with 3 spaces at first and one tab at the end like " Hi\t" I want to copy those whitespace to another string for example string like "hello" would become " hello\t" Is that possible to do easily?

1
  • Yes, using regular expressions. Are you expecting to only take whitespace from the beginning and end of strings? If not, it gets a bit more complicated. Commented Jul 29, 2016 at 14:13

1 Answer 1

1

Yes, this is of course possible. I would use regex for that.

import re

hi = " Hi\t"
hello = "hello"

spaces = re.match(r"^(\s*).+?(\s*)$", hi)
if spaces:
    left, right = spaces.groups()
    string = "{}{}{}".format(left, hello, right)
    print(string)
    # Out: " hello\t"
Sign up to request clarification or add additional context in comments.

2 Comments

The .* in your regex is greedy. To avoid conflicts, you could change the regex to ^(\s*).+?(\s*)$ (i.e. make the mid part lazy).
@jbndlr Indeed, big mistake. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.