I need to split a text string like this: “Hello Everyone Bye Everyone” into two different variables so “Hello Everyone” is one variable and the other variable is “Bye Everyone” What is the easiest way of doing this? I have been experimenting with maxsplit within the split function but no luck. I put an example of what I’m trying below. Any help or insight would be appreciated! Thank you!
message.content.split(' ',maxsplit=1)
I think you can something like below in one line with 2 iterations
message = "Hello Everyone Bye Everyone"
hello_message, bye_message = [msg + ' Everyone' for msg in message.split(' Everyone') if msg]
Assuming your string is always four words split by a single space, you can do something like this:
my_string = "Hello Everyone Bye Everyone"
one_str = ' '.join(my_string.split(' ')[0:2])
two_str = ' '.join(my_string.split(' ')[2:])
This is the solution, updated, for your problem
You must use str.split([sep[, maxsplit]]), because return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done
UPDATE CODE:
s = "Hello Everyone Bye Everyone"
a = s.split('Bye', 1)[0]
b = s.split('Everyone', 1)[1]
print(a)
print(b)
I think it is better to approach the problem by writing a simple function.
def split_by_two(line):
words = line.split(" ")
words_by_two = [" ".join(line_sp[i: i+2]) for i in range(0, len(line_sp), 2)
return words_by_two
return split_by_two(message.content)
By running this function, the output would be groups of two words in list.
Per the subject, I'm trying to print each sentence in a string on a new line. With the current code and output shown below, what's the syntax to return "Correct Output" shown below?
Code
sentence = 'I am sorry Dave. I cannot let you do that.'
def format_sentence(sentence):
sentenceSplit = sentence.split(".")
for s in sentenceSplit:
print s + "."
Output
I am sorry Dave.
I cannot let you do that.
.
None
Correct Output
I am sorry Dave.
I cannot let you do that.
You can do this :
def format_sentence(sentence) :
sentenceSplit = filter(None, sentence.split("."))
for s in sentenceSplit :
print s.strip() + "."
There are some issues with your implementation. First, as Jarvis points out in his answer, if your delimiter is the first or last character in your string or if two delimiter characters are right next to each other, None will be inserted into your array. To fix this, you need to filter out the None values. Also, instead of using the + operator, use formatting instead.
def format_sentence(sentences):
sentences_split = filter(None, sentences.split('.'))
for s in sentences_split:
print '{0}.'.format(s.strip())
You can split the string by ". " instead of ".", then print each line with an additional "." until the last one, which will have a "." already.
def format_sentence(sentence):
sentenceSplit = sentence.split(". ")
for s in sentenceSplit[:-1]:
print s + "."
print sentenceSplit[-1]
Try:
def format_sentence(sentence):
print(sentence.replace('. ', '.\n'))
hey i want to be able to change my string being split at say the third full stop or the 2nd here is my code
file = "hey there. this is some demo code. will you nice people please help me."
i want to split the string after the 2nd full stop so it will look like
"hey there. this is some demo code."
".".join(file.split(".")[2:])
or
file.split(".",2)[2:]
These use str.split() (2/3), str.join() (2/3), and slices (2/3). There's no reason to use loops or regex for this.
I would do something like this:
readf = open("split.txt")
for line in readf:
a=line.split(".")
readf.close()
print (a[:2])
Basically you store the line in a and split it on "." and then use a subsequence which you can use however you like.
e.g. a[2:3] gives u the secound and third line while a[:3] gives you all three.
A rough way to do it would be to use a counter and loop through the string, adding every character until the stopping limit is reached.
firstString = ""
secondString = ""
stopsAllowed = 1
stopsFound = 0
for i in range(0,len(file)):
if file[i] == ".":
stopsFound += 1
if stopsFound <= stopsAllowed:
firstString += file[i]
else:
secondString += file[i]
I have a program that prints out strings from an array like this:
for x in strings
print x,
Which works fine, the strings all print on the same line which is what I want, but then I also have to print out a string that isn't part of the array on a new line. Like this:
for x in strings:
print x,
print second_name
Which ends up all printing on the same line. I want second_name to print on a newline though, how do I do this?
Use the newline character \n:
print '\n' + second_name
I personally think it would be best to use str.join here:
print " ".join(strings)
print second_name
The for-loop just seems like overkill.
The most direct solution is that if you used "print" without final newline in a cycle, add it after this cycle; so the code will look like
for x in strings:
print x,
print ## this terminates the first output line
print second_name
This is kind of the most proper usage of print "API" according to its concepts.
OTOH the answer by K DawG does essentialy the same in other way, putting the default ending '\n' at beginning of the next "print", and, stream nature of stdout makes results of these two variants identical.
NB your construct isn't portable directly to Python3. Python2's print adds a space before each argument unless output isn't at beginning of line. Python3's separator is applied between arguments, but not before the first one in a line. So this manner (cloned from BASIC) isn't perspective and should be replaced with an own manner, like:
out = ''
for x in strings:
out += ' ' + x
print(out[1:])
print(second_name)
but, " ".join(strings) is generally faster and more clear to read.
In C++, \n is used, but what do I use in Python?
I don't want to have to use:
print (" ").
This doesn't seem very elegant.
Any help will be greatly appreciated!
Here's a short answer
x=' '
This will print one white space
print(x)
This will print 10 white spaces
print(10*x)
Print 10 whites spaces between Hello and World
print(f"Hello{x*10}World")
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n) you could just use print without any arguments.
A lone print will output a newline.
print
In 3.x print is a function, therefore:
print()
print("hello" + ' '*50 + "world")
Any of the following will work:
print 'Hello\nWorld'
print 'Hello'
print 'World'
Additionally, if you want to print a blank line (not make a new line), print or print() will work.
First and foremost, for newlines, the simplest thing to do is have separate print statements, like this:
print("Hello")
print("World.")
#the parentheses allow it to work in Python 2, or 3.
To have a line break, and still only one print statement, simply use the "\n" within, as follows:
print("Hello\nWorld.")
Below, I explain spaces, instead of line breaks...
I see allot of people here using the + notation, which personally, I find ugly.
Example of what I find ugly:
x=' ';
print("Hello"+10*x+"world");
The example above is currently, as I type this the top up-voted answer. The programmer is obviously coming into Python from PHP as the ";" syntax at the end of every line, well simple isn't needed. The only reason it doesn't through an error in Python is because semicolons CAN be used in Python, really should only be used when you are trying to place two lines on one, for aesthetic reasons. You shouldn't place these at the end of every line in Python, as it only increases file-size.
Personally, I prefer to use %s notation. In Python 2.7, which I prefer, you don't need the parentheses, "(" and ")". However, you should include them anyways, so your script won't through errors, in Python 3.x, and will run in either.
Let's say you wanted your space to be 8 spaces,
So what I would do would be the following in Python > 3.x
print("Hello", "World.", sep=' '*8, end="\n")
# you don't need to specify end, if you don't want to, but I wanted you to know it was also an option
#if you wanted to have an 8 space prefix, and did not wish to use tabs for some reason, you could do the following.
print("%sHello World." % (' '*8))
The above method will work in Python 2.x as well, but you cannot add the "sep" and "end" arguments, those have to be done manually in Python < 3.
Therefore, to have an 8 space prefix, with a 4 space separator, the syntax which would work in Python 2, or 3 would be:
print("%sHello%sWorld." % (' '*8, ' '*4))
I hope this helps.
P.S. You also could do the following.
>>> prefix=' '*8
>>> sep=' '*2
>>> print("%sHello%sWorld." % (prefix, sep))
Hello World.
rjust() and ljust()
test_string = "HelloWorld"
test_string.rjust(20)
' HelloWorld'
test_string.ljust(20)
'HelloWorld '
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
this is how to print whitespaces in python.
import string
string.whitespace
'\t\n\x0b\x0c\r '
i.e .
print "hello world"
print "Hello%sworld"%' '
print "hello", "world"
print "Hello "+"world
Sometimes, pprint() in pprint module works wonder, especially for dict variables.
simply assign a variable to () or " ", then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
To print any amount of lines between printed text use:
print("Hello" + '\n' *insert number of whitespace lines+ "World!")
'\n' can be used to make whitespace, multiplied, it will make multiple whitespace lines.
In Python2 there's this.
def Space(j):
i = 0
while i<=j:
print " ",
i+=1
And to use it, the syntax would be:
Space(4);print("Hello world")
I haven't converted it to Python3 yet.
A lot of users gave you answers, but you haven't marked any as an answer.
You add an empty line with print().
You can force a new line inside your string with '\n' like in print('This is one line\nAnd this is another'), therefore you can print 10 empty lines with print('\n'*10)
You can add 50 spaces inside a sting by replicating a one-space string 50 times, you can do that with multiplication 'Before' + ' '*50 + 'after 50 spaces!'
You can pad strings to the left or right, with spaces or a specific character, for that you can use .ljust() or .rjust() for example, you can have 'Hi' and 'Carmen' on new lines, padded with spaces to the left and justified to the right with 'Hi'.rjust(10) + '\n' + 'Carmen'.rjust(10)
I believe these should answer your question.