This question already has answers here:
How do I remove a substring from the end of a string?
(23 answers)
Closed 2 years ago.
I am kind of noob in python and struck in middle of code. I want to trim my string.
For example- my string is "bangalore store 1321" and i want to trim it to "banglore"
Looks like you want to keep the first word (which is not "trimming" though). So you do two things
break the string into a list of words (where "word" is something separated by spaces)
take the first element of that list
words = mystring.split(' ')
result = words[0]
For a slicing answer:
def sub_string(str, start,end):
return str[start:end]
You can also use split, by definition, this splits by spaces, if any other delimiter needed, you can identity it inside the split arguments split(',')
def split_string(str):
return str.split()
This function will return an array of strings. Choose whichever you want from this array
str="bangalore store 1321"
print(str.split(' ')[0])
Output
bangalore
You can use str's partition method to avoid creating a list like str.split
>>> first_word, _, _ = s.partition(' ') # _ is a convention for a throwaway variable
>>> print(first_word)
bangalore
str.partition takes one argument - the separator - and returns the parts of the string before and after the first occurrence of the separator.
Related
This question already has answers here:
Underscore _ as variable name in Python [duplicate]
(3 answers)
Closed 1 year ago.
import numpy
n,m=map(int, input().split())
arr=numpy.array([input().strip().split() for _ in range(n)],int)
print (numpy.transpose(arr))
print(arr.flatten())
Why should there be an underscore before "in range" in the third line? It would also be useful if someone explained why .strip and .split need to be applied here.
Thanks a lot!
_ is just a variable, it could be named differently, for example i. _ is just a conventional name for unused variables. In this case, you execute input().strip().split() n times in exactly the same way, without caring which iteration (i) it is.
.split() splits the input string by spaces, for example:
>>> '1 2 3'.split()
['1', '2', '3']
.strip() trims whitespace at the edges:
>>> ' 1 2 3 '.strip()
'1 2 3'
You can read more about these methods by googling the docs or, even simpler, running help(str.split) in an inerpreter
In Python, the underscore holds the result of the last executed expression.
In some cases, it is used to replace a variable that will not be used.
In your example, as you just need to loop n number of times without needing to know the value of each iteration, you can use for _ in range(n) instead of for i in range(n).
You can find more information about the underscore in Python here: What is the purpose of the single underscore "_" variable in Python?
As for the strip and split methods, here is a quick explanation based on the Python documentation.
str.strip: Return a copy of the string with the leading and trailing characters removed.
str.split: Return a list of the words in the string, using sep as the delimiter string.
So from your example, your code takes the input of the user, removes any leading and trailing characters with strip, and split the input into a list of words.
For example, if the user input is Hello World! , the result will be: ["Hello", "World!"]
Hope that helps!
This question already has answers here:
Capitalize a string
(9 answers)
Closed 4 years ago.
If you've got a string containing for example "how are you?", I would do stringname.replace("how", "How") to have the first word written in Capital H.
So far so good.
The problem now is, I'm writing this script which at some point accesses the Open Weather Map, and the words are driving me crazy.
Until now I just did a
weather2 = self.weather.replace("partly", "Partly")
weather3 = weather2.replace("cloudy", "Cloudy")
weather4 = weather3.replace("foggy", "Foggy")
weather5 = weather4.replace("sunny", "Sunny")
weather6 = weather5.replace("rain", "Rain") #and so on
But I can't have 20 .replace().
So I was thinking, and here comes my question:
Could I create two lists, one containing the OWM originals, and the other list with the Words it shall be replaced with, and do something like
for name in names
do something
To capitalize first letter use mystring.title()
for name in names:
name.title()
https://www.geeksforgeeks.org/title-in-python/
If you want to capitalize the string you can use .capitalize()
self.weather= self.weather.capitalize()
or if you want to use a list/dictionary solution:
dictionary={'cloudy':'Cloudy','foggy':'Foggy','sunny':'Sunny','rain':'Rain'}
if self.weather in dictionary:
self.weather=dictionary[self.weather]
use .capitalize() function. .title() function also behaves similar. but it will capitalize all the first letter in a string if your string contains more than one word.
for name in names:
name.capitalize()
This question already has answers here:
Split a string by a delimiter in python
(5 answers)
Closed 5 years ago.
If given the string "John Doe;Lodging;123;050617", which is a line within a file, I need to remove everything before and including the first semicolon, and after and including the last one. How can I do that without removing my ability to later split the remaining substring?
Previous questions do not address removing the portions once separated while retaining the portion needed for further use.
Stepwise for clarity:
string = "John Doe;Lodging;123;050617"
lst = string.split(';')
lst = lst[1:-1]
string = ';'.join(lst)
print(string)
>>> 'Lodging;123'
As one line:
';'.join('John Doe;Lodging;123;050617'.split(';')[1:-1])
>>> 'Lodging;123'
s = "John Doe;Lodging;123;050617"
new_s = ';'.join(s.split(';')[1:-1])
This will make new_s = 'Lodging;123'
test = "John Doe;Lodging;123;050617"
';'.join(test.split(';')[1:-1])
The find method will give you the index of the first instance of a character in a string
original_s="John Doe;Lodging;123;050617"
idx = original_s.find(';')
new_s = original_s[i+1:]
print(new_s)
There are a few methods you could try. The simplest one is to split the string and reassemble it:
data = 'John Doe;Lodging;123;050617'
';'.join(data.split(';')[1:-1])
You could also use find and rfind (like find, but from the end of the string backwards:
data[data.find(';')+1:data.rfind(';')]
There's also partition and rpartition:
first, sep, remainder = data.partition(';')
middle, sep, final = remainder.rpartition(';')
Use str.partition and str.rpartition.
s = "John Doe;Lodging;123;050617"
s.partition(';')[-1].rpartition(';')[0] # Lodging;123
In terms of efficiency, this is probably the best solution. However, I find the split/join method more readable.
Try:
s = "John Doe;Lodging;123;050617"
print(';'.join(s.split(';')[1:-1]))
Try this: use str.find() function to locate the first occurance of ';' and then substring from that point to the end using [:]
aStr = "John Doe;Lodging;123;050617"
aStr = aStr[aStr.find(';')+1:]
print(aStr)
Lodging;123;050617
Consider the following example
a= 'Apple'
b = a.split(',')
print(b)
Output is ['Apple'].
I am not getting why is it returning a list even when there is no ',' character in Apple
There might be case when we use split method we are expecting more than one element in list but since we are splitting based on separator not present in string, there will be only one element, wouldn't it be better if this mistake is caught during this split method itself
The behaviour of a.split(',') when no commas are present in a is perfectly consistent with the way it behaves when there are a positive number of commas in a.
a.split(',') says to split string a into a list of substrings that are delimited by ',' in a; the delimiter is not preserved in the substrings.
If 1 comma is found you get 2 substrings in the list, if 2 commas are found you get 3 substrings in the list, and in general, if n commas are found you get n+1 substrings in the list. So if 0 commas are found you get 1 substring in the list.
If you want 0 substrings in the list, then you'll need to supply a string with -1 commas in it. Good luck with that. :)
The docstring of that method says:
Return a list of the words in the string S, using sep as the delimiter string.
The delimiter is used to separate multiple parts of the string; having only one part is not an error.
That's the way split() function works. If you do not want that behaviour, you can implement your my_split() function as follows:
def my_split(s, d=' '):
return s.split(d) if d in s else s
This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 7 years ago.
I know in python there is a way to turn a word or string into a list using list(), but is there a way of turning it back, I have:
phrase_list = list(phrase)
I have tried to change it back into a string using repr() but it keeps the syntax and only changes the data type.
I am wondering if there is a way to turn a list, e.g. ['H','e','l','l','o'] into: 'Hello'.
Use the str.join() method; call it on a joining string and pass in your list:
''.join(phrase)
Here I used the empty string to join the elements of phrase, effectively concatenating all the characters back together into one string.
Demo:
>>> phrase = ['H','e','l','l','o']
>>> ''.join(phrase)
'Hello'
Using ''.join() is the best approach but you could also you a for loop. (Martijn beat me to it!)
hello = ['H','e','l','l','o']
hello2 = ''
for character in hello:
hello2 += character