Using Python to Split Text String into Two Variables - python

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.

Related

Removing numbers and _ symbol from a parsed URL using re module and sub() function in Python

I'm trying to exclude "numbers" and the symbols "-" and "_" from a string that I got parsing a URL.
For example,
string1 = 'historical-fiction_4'
string_cleaned = re.sub("[^a-z]", "", string1)
print(string1)
print(string_cleaned)
historical-fiction_4
historicalfiction
With re.sub("[^a-z]") I got just the strings from a to z but instead of getting the string "historicalfiction" I would like to get "Historical Fiction".
More or less all my data is collected with this structure "name1-name2_number".
If anyone can help me improve my re.sub() call I'll really appreciate. Thanks a lot!
You can use str.title() to capitalize every word:
import re
string1 = "historical-fiction_4"
string1 = re.sub(r"[^a-z]", " ", string1).strip().title()
print(string1)
Prints:
Historical Fiction
It appears to me that your logic is that you want to replace dashes with spaces, but completely strip off underscore and digits. If so, then use two separate calls to replace:
inp = "historical-fiction_4"
output = re.sub(r'[0-9_]+', '', inp.replace("-", " "))
print(output) # historical fiction

title() method in python writing functions when word like aren't

using function
def make_cap(sentence):
return sentence.title()
tryining out
make_cap("hello world")
'Hello World'
# it workd but when I have world like "aren't" and 'isn't". how to write function for that
a = "I haven't worked hard"
make_cap(a)
"This Isn'T A Right Thing" # it's wrong I am aware of \ for isn\'t but confused how to include it in function
This should work:
def make_cap(sentence):
return " ".join(word[0].title() + (word[1:] if len(word) > 1 else "") for word in sentence.split(" "))
It manually splits the word by spaces (and not by any other character), and then capitalizes the first letter of each token. It does this by separating that first letter out, capitalizing it, and then concatenating the rest of the word. I used a ternary if statement to avoid an IndexError if the word is only one letter long.
Use .capwords() from the string library.
import string
def make_cap(sentence):
return string.capwords(sentence)
Demo: https://repl.it/repls/BlankMysteriousMenus
I found this method to be very helpful for formatting all different types of texts as titles.
from string import capwords
text = "I can't go to the USA due to budget concerns"
title = ' '.join([capwords(w) if w.islower() else w for w in text.split()])
print(title) # I Can't Go To The USA Due To Budget Concerns

Python Split a string by diffrent . full stops

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]

How to make a sentence in Python?

Im using Python 3.2 on Win7. I wrote this using ASCII code:
print (''.join((chr(i+22) for i in (50,75,90,90,99))))
print (''.join((chr(j+22) for j in (44,83,92,94,82,78,75,99,11))))
which as a result writes:
Happy
Birthday!
Now, I'd like to join these two words in one sentence, so it writes:
Happy Birthday!
It seems like a simple thing to do, but I'm new at Python, so could someone help me?
Thanks :)
Do you mean like this?
print (''.join((chr(i+22) for i in (50,75,90,90,99,10,44,83,92,94,82,78,75,99,11))))
To have them on the same line, and the end of the first print statement, type in the parameter end=" ", so the next print statement will print on the same line.
its simple.. just use + operator.
print (''.join((chr(i+22) for i in (50,75,90,90,99))))+" "+ (''.join((chr(j+22) for j in (44,83,92,94,82,78,75,99,11))))
You can ask print() not to add a newline:
print(..., end='')
end, by default, is set to \n.
For your sample, that'd be:
print(''.join((chr(i+22) for i in (50,75,90,90,99))), end=' ')
print(''.join((chr(j+22) for j in (44,83,92,94,82,78,75,99,11))))
printing a space instead of a newline after Happy.
You could also include the space in your list of ASCII codepoints; ASCII space is 32, but you add 22 to your values, so including 10 should do it:
print(''.join((chr(i+22) for i in (50,75,90,90,99,10,44,83,92,94,82,78,75,99,11))))
Print your output using string formatting:
s1 = ''.join((chr(i+22) for i in (50,75,90,90,99)))
s2 = ''.join((chr(j+22) for j in (44,83,92,94,82,78,75,99,11))))
print("%s %s" % (s1, s2))

Capitalize a string

Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?
For example:
asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest
I would like to be able to do all string lengths as well.
>>> b = "my name"
>>> b.capitalize()
'My name'
>>> b.title()
'My Name'
#saua is right, and
s = s[:1].upper() + s[1:]
will work for any string.
What about your_string.title()?
e.g. "banana".title() -> Banana
s = s[0].upper() + s[1:]
This should work with every string, except for the empty string (when s="").
this actually gives you a capitalized word, instead of just capitalizing the first letter
cApItAlIzE -> Capitalize
def capitalize(str):
return str[:1].upper() + str[1:].lower().......
for capitalize first word;
a="asimpletest"
print a.capitalize()
for make all the string uppercase use the following tip;
print a.upper()
this is the easy one i think.
You can use the str.capitalize() function to do that
In [1]: x = "hello"
In [2]: x.capitalize()
Out[2]: 'Hello'
Hope it helps.
Docs can be found here for string functions https://docs.python.org/2.6/library/string.html#string-functions
Below code capitializes first letter with space as a separtor
s="gf12 23sadasd"
print( string.capwords(s, ' ') )
Gf12 23sadasd
str = str[:].upper()
this is the easiest way to do it in my opinion

Categories

Resources