This question already has answers here:
Split a string by a delimiter in python
(5 answers)
Closed 2 years ago.
I am trying to print by breaking a line based on character \n (new line). Below is the example:
line = "This is list\n 1.Cars\n2.Books\n3.Bikes"
I want to print the output as below:
This is list:
1.Cars
2.Books
3.Bikes
I used code as below:
line1 = line.split()
for x in line1:
print(x)
But its printing each word in different line. How to split the string based on only "\n"
Regards,
Arun Varma
The argument to split() specifies the string to use as a delimiter. If you don't give an argument it splits on any whitespace by default.
If you only want to split at newline characters, use
line1 = line.split('\n')
There's also a method specifically for this:
line1 = line.splitlines()
Related
This question already has answers here:
Python split() without removing the delimiter [duplicate]
(4 answers)
Closed 11 months ago.
Is it possible to separate the string "a!b!" into two strings "a!" and "b!" and store that in a list? I have tried the split() function (and even with the delimiter "!"), but it doesn't seem to give me the right result that I want. Also, the character "!" could be any character.
How about :
string = 'a!ab!b!'
deliminator = '!'
word_list = [section+deliminator for section in string.split(deliminator) if section]
print(word_list)
Output :
['a!', 'ab!', 'b!']
split() is used when you need to seperate a string with particular character. If you want split a string into half, Try this
s = "a!b!"
l = [s[ : len(s)//2], s[len(s)//2 : ]]
# output : ["a!", "b!"]
This question already has answers here:
Split Strings into words with multiple word boundary delimiters
(31 answers)
Closed 3 years ago.
I have the following data in a csv file:
IDA/IDB/type/timestamp valueoftype
A1/B1/a/1575033906 4
A1/B1/b/1575033906 5
A1/B1/c/1575033906 3
A1/B2/a/1575033906 5
A2/B3/a/1575033906 6
A1/B2/b/1575033906 7
A1/B2/c/1575033906 85
A2/B3/b/1575033906 6
A2/B3/c/1575033906 4
.
.
.
A1/B1/a/1575033909 5
A1/B1/b/1575033909 6
A1/B1/c/1575033909 4
I want to use a regular expression so that I can read each line of the file in order to split it based on two delimiters. In my case those delimiters are " " and "/". So in the end, I want to have this :
['A1','B1','a','1575033906','4']
Here is the code I used:
for line in f:
print(line)
x = re.split(r'[ /]+', line)
print(x)
And the results it gives me is this:
['A1','B1','a','1575033906','4\n']
How could I exclude the "\n" character from getting into that last position?
strip or rstrip it away:
x = re.split(r'[ /]+', line.strip())
If there's precious whitespace at the beginning of the line, use rstrip to strip from the right:
>>> ' w t\n'.rstrip()
' w t'
This question already has answers here:
How can I do a line break (line continuation) in Python?
(10 answers)
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 5 months ago.
I have some strings to be concatenated and the resultant string will be quite long. I also have some variables to be concatenated.
How can I combine both strings and variables so the result would be a multiline string?
The following code throws error.
str = "This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3" ;
I have tried this too
str = "This is a line" \
str1 \
"This is line 2" \
str2 \
"This is line 3" ;
Please suggest a way to do this.
There are several ways. A simple solution is to add parenthesis:
strz = ("This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3")
If you want each "line" on a separate line you can add newline characters:
strz = ("This is a line\n" +
str1 + "\n" +
"This is line 2\n" +
str2 + "\n" +
"This is line 3\n")
Python 3: Formatted Strings
As of Python 3.6 you can use so-called "formatted strings" (or "f strings") to easily insert variables into your strings. Just add an f in front of the string and write the variable inside curly braces ({}) like so:
>>> name = "John Doe"
>>> f"Hello {name}"
'Hello John Doe'
To split a long string to multiple lines surround the parts with parentheses (()) or use a multi-line string (a string surrounded by three quotes """ or ''' instead of one).
1. Solution: Parentheses
With parentheses around your strings you can even concatenate them without the need of a + sign in between:
a_str = (f"This is a line \n{str1}\n"
f"This is line 2 \n{str2}\n"
f"This is line 3") # no variable in this line, so a leading f"" is optional but can be used to properly align all lines
Good to know: If there is no variable in a line, there is no need for a leading f for that line.
Good to know: You could archive the same result with backslashes (\) at the end of each line instead of surrounding parentheses but accordingly to PEP8 you should prefer parentheses for line continuation:
Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
2. Solution: Multi-Line String
In multi-line strings you don't need to explicitly insert \n, Python takes care of that for you:
a_str = f"""This is a line
{str1}
This is line 2
{str2}
This is line 3"""
Good to know: Just make sure you align your code correctly otherwise you will have leading white space in front each line.
By the way: you shouldn't call your variable str because that's the name of the datatype itself.
Sources for formatted strings:
What's new in Python 3.6
PEP498
Python isn't php and you have no need to put $ before a variable name.
a_str = """This is a line
{str1}
This is line 2
{str2}
This is line 3""".format(str1="blabla", str2="blablabla2")
I would add everything I need to concatenate to a list and then join it on a line break.
my_str = '\n'.join(['string1', variable1, 'string2', variable2])
This question already has answers here:
How to remove \n from a list element?
(15 answers)
Closed 7 years ago.
How can I delete a /n linebreak at the end of a String ?
I´m trying to read two strings from an .txt file and want to format them with os.path.join() method after I "cleared" the string.
Here you can see my try with dummy data:
content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
for string in content:
print(string)
if string.endswith('\\\n'):
string = string[0:-2]
print(content)
You can not update a string like you are trying to. Python strings are immutable. Every time you change a string, new instance is created. But, your list still refers to the old object. So, you can create a new list to hold updated strings. And to strip newlines you can use rstrip function. Have a look at the code below,
content = ['Source=C:\\Users\\app\n', 'Target=C:\\Apache24\\htdocs']
updated = []
for string in content:
print(string)
updated.append(string.rstrip())
print(updated)
You can use rstrip function. it trims any 'empty' string including \n from the string, like below:
>>> a = "aaa\n"
>>> print a
aaa
>>> a.rstrip()
'aaa'
To remove only \n use this:
string = string.rstrip('\n')
When you do string[0:-2] you are actually removing 2 characters from the end, while \n is one character.
try:
content = map(lambda x: x.strip(), content)
This question already has answers here:
Python - Count number of words in a list strings
(8 answers)
Closed 8 years ago.
I want to count the total no of words in each line in a file and print them.I tried
with codecs.open('v.out','r',encoding='utf-8') as f:
for line in f.readlines():
words = len(line.strip(' '))
print words
the input file is:
hello
try it
who knows
it may work
the output that I get is:
6
7
10
12
but what I need is:
1
2
2
3
is there any function that I can use? I have to print the first word of each line in a file, and similarly print the middle word and the last word of the line into separate files.
You are stripping spaces from the ends, not splitting the words. You are counting the remaining characters now, not words.
Use str.split() instead:
words = len(line.split())
No arguments required, or use None; it'll strip whitespace from the ends, and split on arbitrary-width whitespace, giving you words:
>>> 'it may work'.split()
['it', 'may', 'work']
>>> len('it may work'.split())
3
You were so close. This line:
words = len(line.strip(' '))
should be:
words = len(line.split(' '))
strip removes characters from the start and end of the string, split breaks the string up into a list of strings.