I have four strings and any of them can be empty. I need to join them into one string with spaces between them. If I use:
new_string = string1 + ' ' + string2 + ' ' + string3 + ' ' + string4
The result is a blank space on the beginning of the new string if string1 is empty. Also, I have three blank spaces if string2 and string3 are empty.
How can I easily join them without blank spaces when I don't need them?
>>> strings = ['foo','','bar','moo']
>>> ' '.join(filter(None, strings))
'foo bar moo'
By using None in the filter() call, it removes all falsy elements.
If you KNOW that the strings have no leading/trailing whitespace:
>>> strings = ['foo','','bar','moo']
>>> ' '.join(x for x in strings if x)
'foo bar moo'
otherwise:
>>> strings = ['foo ','',' bar', ' ', 'moo']
>>> ' '.join(x.strip() for x in strings if x.strip())
'foo bar moo'
and if any of the strings have non-leading/trailing whitespace, you may need to work harder still. Please clarify what it is that you actually have.
strings = ['foo','','bar','moo']
' '.join([x for x in strings if x is not ''])
'foo bar moo'
Related
user_words = raw_input()
word_list = user_words.split()
user_words = []
for word in word_list:
user_words.append(word.capitalize())
user_words = " ".join(user_words)
print(user_words)
Current Output:
Input:
hello world(two spaces in between)
Output:
Hello World
Desired Output:
Input:
hello world(two spaces in between)
Output:
Hello World(two spaces in between)
Note: I want to be able to split the string by spaces, but still have the extra spaces between words in the original string that's inputted by the user.
If you split using the space character, you'll get extra '' in your list
>>> "Hello world".split()
['Hello', 'world']
>>> "Hello world".split(' ')
['Hello', '', 'world']
Those generate the extra spaces again after a join
>>> ' '.join(['Hello', '', 'world'])
'Hello world'
Use re.split for this and join by the space original string has.
user_words = raw_input()
word_list = re.split(r"(\s+)",user_words)
user_words = []
user_words.append(word_list[0].capitalize())
user_words.append(word_list[2].capitalize())
user_words = word_list[1].join(user_words)
print(user_words)
I found that I can join them with '-'.join(name) but I dont want to add any character. Lets say I have
['stanje1', '|', 'st6', ',' 'stanje2', '|', '#']
and I want to be like this
stanje1|st6,stanje2|#
Just ommit the -:
''.join(name)
In that case, you can just do it as:
''.join(name)
>>> name = ['stanje1', '|', 'st6', ',' 'stanje2', '|', '#']
>>> print ''.join(name)
stanje1|st6,stanje2|#
This will join the string with no intermediate string.
Examples
>>> s = ['Hello', 'World']
>>> print ''.join(s)
HelloWorld
>>> print '-'.join(s)
Hello-World
How can I strip the comma from a Python string such as Foo, bar? I tried 'Foo, bar'.strip(','), but it didn't work.
You want to replace it, not strip it:
s = s.replace(',', '')
Use replace method of strings not strip:
s = s.replace(',','')
An example:
>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True
unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))
This will strip all commas from the text and left justify it.
for row in inputfile:
place = row['your_row_number_here'].strip(', ')
With Python I know that the "\n" breaks to the next line in a string, but what I am trying to do is replace every "," in a string with a '\n'. Is that possible? I am kind of new to Python.
Try this:
text = 'a, b, c'
text = text.replace(',', '\n')
print text
For lists:
text = ['a', 'b', 'c']
text = '\n'.join(text)
print text
>>> str = 'Hello, world'
>>> str = str.replace(',','\n')
>>> print str
Hello
world
>>> str_list=str.split('\n')
>>> print str_list
['Hello', ' world']
For futher operations you may check: http://docs.python.org/library/stdtypes.html
You can insert a literal \n into your string by escaping the backslash, e.g.
>>> print '\n'; # prints an empty line
>>> print '\\n'; # prints \n
\n
The same principle is used in regular expressions. Use this expresion to replace all , in a string with \n:
>>> re.sub(",", "\\n", "flurb, durb, hurr")
'flurb\n durb\n hurr'
I've split a string by [ and ] but I want these characters to still appear. How do I do this?
words = [beginning for ending in x.split('[') for beginning in ending.split(']')]
I think you need re.split to do this easily:
>>> import re
>>> s = 'Hello, my name is [name] and I am [age] years old'
>>> re.split(r'(\[|\])', s)
['Hello, my name is ', '[', 'name', ']', ' and I am ', '[', 'age', ']', ' years old']
Would need to know more about the context of your list and what x, beginning, and ending are, but here are some suggestions.
You can add [ and ] to each item in the list, and return a new list, like this:
["[%s]" % s for s in some_list]
Or, string.join will return a string from the items in a list joined by a given string:
"[".join(some_list)