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'
Related
I need to convert 'a b c' to 'abc' so made this code:
string = 'a b c'
result = [ch for ch in string if (ch != ' ')]
print(type(result))
result = str(result)
print(type(result))
print(result)
result of this code is expected as:
<class 'list'>
<class 'str'>
'abc'
but result is as:
<class 'list'>
<class 'str'>
['a', 'b', 'c']
why result is printed list? this makes faults in other part of my code.
str() on a list does not magically turn said list into a no delimiter string. When you do
str(['a', 'b', 'c']) - what you actually get is '['a', 'b', 'c']', which is indeed a string.
If you'd like the result to be 'abc' please, use .join.
''.join(['a', 'b', 'c'])
Output-
'abc'
Here result = [ch for ch in string if (ch != ' ')] you eliminate spaces and save the chars into list. But to have string again, you need to join them:
string = 'a b c'
result = [ch for ch in string if (ch != ' ')]
s = "".join(result)
print(s) # abc
Here is the related doc page.
you can try this :
string = 'a b c'
print(string.replace(' ' ,''))
Output :
abc
you are getting a list cause you are using list comprehension.
here I have split the string into spaces using the string method split
which returns a list
I have printed the type of the list and type of element in the list
and joined them back using the string method join
string = 'a b c'
string = string.split(' ')
print(type(string))
print(type(string[0]))
print("".join(string))
The line of code
result = [ch for ch in string if (ch != ' ')]
is an example of a list comprehension in Python.
The for loop within this list takes each value from the string, one at a time, and places it into the list - this is why the list ['a', 'b', 'c'] appears in your code.
To obtain a string without spaces from a string with spaces:
string = 'a b c'
# obtain characters from the string that are not spaces
result = [ch for ch in string if (ch != ' ')]
# put the string back together without spaces
string_no_spaces = ''.join(result)
>>>'abc'
What does str(['a', 'b', 'c']) actually do is, str calls up the __str__ method of the given object (which is list now) to its constructor which makes: '['a', 'b', 'c']' string.
why result is printed list? this makes faults in other part of my code.
What print does before dumping is str('['a', 'b', 'c']'), which effectively does nothing here, printing it just strips out ' making you think that it's a list.
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
I have several python strings from which I want unwanted characters removed.
Examples:
"This is '-' a test"
should be "This is a test"
"This is a test L)[_U_O-Y OH : l’J1.l'}/"
should be "This is a test"
"> FOO < BAR"
should be "FOO BAR"
"I<<W5§!‘1“¢!°\" I"
should be ""
(because if only words are extracted then it returns I W I and none of them form words)
"l‘?£§l%nbia ;‘\\~siI.ve_rswinq m"
should be ""
"2|'J]B"
should be ""
this is what I have so far, however, it is not keeping the original spaces between words.
>>> line = re.sub(r"\W+","","This is '-' a test")
>>> line
'Thisisatest'
>>> line = re.sub(r"\W+","","This is a test L)[_U_O-Y OH : l’J1.l'}/")
>>> line
'ThisisatestL_U_OYOHlJ1l'
#although i would prefer this to be "This is a test" but if not possible i would
prefer "This is a test L_U_OYOHlJ1l"
>>> line = re.sub(r"\W+","","> FOO < BAR")
>>> line
'FOOBAR'
>>> line = re.sub(r"\W+","","I<<W5§!‘1“¢!°\" I")
>>> line
'IW51I'
>>> line = re.sub(r"\W+","","l‘?£§l%nbia ;‘\\~siI.ve_rswinq m")
>>> line
'llnbiasiIve_rswinqm'
>>> line = re.sub(r"\W+","","2|'J]B")
>>> line
'2JB'
I will be filtering the regex cleaned words through a list of predefined words later.
I'd go with a split and filter, like this:
' '.join(word for word in line.split() if word.isalpha() and word.lower() in list)
This will remove all non-alphabetic words and alphabetic words that are not in the list.
Examples:
def myfilter(string):
words = {'this', 'test', 'i', 'a', 'foo', 'bar'}
return ' '.join(word for word in line.split() if word.isalpha() and word.lower() in words)
>>> myfilter("This is '-' a test")
'This a test'
>>> myfilter("This is a test L)[_U_O-Y OH : l’J1.l'}/")
'This a test'
>>> myfilter("> FOO < BAR")
'FOO BAR'
>>> myfilter("I<<W5§!‘1“¢!°\" I")
'I'
>>> myfilter("l‘?£§l%nbia ;‘\\~siI.ve_rswinq m")
''
>>> myfilter("2|'J]B")
''
This one clears out any group of non-space symbols with at least one non alphabetic character. It will leaves some unwanted group of letters though :
re.sub(r"\w*[^a-zA-Z ]+\w*","","This is a test L)[_U_O-Y OH : l’J1.l'}/")
gives :
'This is a test OH '
It will also leave groups of more than one space :
re.sub(r"[^a-zA-Z ]+\w*","","This is '-' a test")
'This is a test' # two spaces
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(', ')