Python 删除字符串中每一行的最后一个字符
我有一个带有列Python 删除字符串中每一行的最后一个字符,python,Python,我有一个带有列键的数据帧,我需要从每个字符串中删除最后一个字符 id keys 123 "https://www.cosmopolitan.com/entertainment/tv/a46533/" 124 "https://www.bazaar.com/entertainment/tv/a46533/" 目前,我正在尝试创建一个返回干净字符串的函数,稍后我会将该函数应用于df。我尝试了以下方法: url_test = "https://www.cos
键的数据帧,我需要从每个字符串中删除最后一个字符
id keys
123 "https://www.cosmopolitan.com/entertainment/tv/a46533/"
124 "https://www.bazaar.com/entertainment/tv/a46533/"
目前,我正在尝试创建一个返回干净字符串的函数,稍后我会将该函数应用于df。我尝试了以下方法:
url_test = "https://www.cosmopolitan.com/entertainment/tv/"
def clean_string(url):
for string in url:
new_string = string[:-1]
return new_string
clean_string(url_test)
它返回一个空字符串。我希望它返回“url\u test=”https://www.cosmopolitan.com/entertainment/tv“
只要删除for循环,就可以传入一个字符串,然后对字符进行迭代,返回第一个字符,而不返回第一个字符,因此是一个空字符串。”
def clean_string(url):
return url[:-1]
虽然我不确定你是否还需要一个函数来完成这项工作
如果您只是想删除尾部斜杠,您可能更喜欢使用rstrip
return url.rstrip("/")
你可以用熊猫
e、 g
将修剪字符串中的最后一个字符。这允许您一次对整个列而不是一行进行操作。如果列键
包含str
类型的所有值,并且您希望将函数应用(或者更确切地说,map
)到列,您可以简单地使用rstrip
(或者只是剥离),而不定义函数
假设给定的数据帧命名为df
,请尝试:
new_keys=df['keys'].str.rstrip('/'))
新的按键是熊猫系列。完美!我确实需要一个函数,因为我需要将它应用到熊猫df。这很有效!谢谢。
import pandas as pd
test = pd.Series([
"https://www.cosmopolitan.com/entertainment/tv/a46533/",
"https://www.bazaar.com/entertainment/tv/a46533/"])
test = test.str[:-1]